Rails HABTM with polymorphic relationships

ぐ巨炮叔叔 提交于 2019-12-04 13:30:25

问题


I have a table Category which can have many Businesses and Posts. And a Business/Post can have many Categories so I created a polymorphic tabled called CategoryRelationship to break up the many to many relationship.

Business model has these relationships:

  has_many :categories, through: :category_relationships, :source => :category_relationshipable, :source_type => 'Business'
  has_many :category_relationships

CategoryRelationship model has these relationships:

 attr_accessible :category_id, :category_relationship_id, :category_relationship_type

  belongs_to :category_relationshipable, polymorphic: true
  belongs_to :business
  belongs_to :post
  belongs_to :category

Category has these relationships:

has_many :category_relationships
  has_many :businesses, through: :category_relationships
  has_many :posts, through: :category_relationships

Post would have similar relationships as Business.

So now when I run Business.first.categories I get the error:

Business Load (6.1ms)  SELECT "businesses".* FROM "businesses" LIMIT 1
  Business Load (2.5ms)  SELECT "businesses".* FROM "businesses" INNER JOIN "category_relationships" ON "businesses"."id" = "category_relationships"."category_relationshipable_id" WHERE "category_relationships"."business_id" = 3 AND "category_relationships"."category_relationshipable_type" = 'Business'
ActiveRecord::StatementInvalid: PG::Error: ERROR:  column category_relationships.business_id does not exist
LINE 1: ...lationships"."category_relationshipable_id" WHERE "category_...
                                                             ^
: SELECT "businesses".* FROM "businesses" INNER JOIN "category_relationships" ON "businesses"."id" = "category_relationships"."category_relationshipable_id" WHERE "category_relationships"."business_id" = 3 AND "category_relationships"."category_relationshipable_type" = 'Business'

How do I structure the relationships so this works?


回答1:


Similar questions here: Rails polymorphic has_many :through And here: ActiveRecord, has_many :through, and Polymorphic Associations

I think it should be something like this:

class Category
  has_many :categorizations
  has_many :businesses, through: :categorizations, source: :categorizable, source_type: 'Business'
  has_many :posts, through: :categorizations, source: :categorizable, source_type: 'Post'
end

class Categorization
  belongs_to :category
  belongs_to :categorizable, polymorphic: true
end

class Business #Post looks the same
  has_many :categorizations, as: :categorizeable
  has_many :categories, through: :categorizations
end


来源:https://stackoverflow.com/questions/17280793/rails-habtm-with-polymorphic-relationships

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!