我有一张表Category
,可以有很多Businesses
和Posts
。 Business
/ Post
可以包含多个Categories
,因此我创建了一个名为CategoryRelationship
的多态表,以打破多对多的关系。
Business
模型具有以下关系:
has_many :categories, through: :category_relationships, :source => :category_relationshipable, :source_type => 'Business'
has_many :category_relationships
CategoryRelationship
模型具有以下关系:
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_many :category_relationships
has_many :businesses, through: :category_relationships
has_many :posts, through: :category_relationships
Post
与Business
具有相似的关系。
所以现在当我运行Business.first.categories
时,我收到错误:
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'
如何构建关系以便这样做?
答案 0 :(得分:12)
此处有类似的问题:Rails polymorphic has_many :through 在这里:ActiveRecord, has_many :through, and Polymorphic Associations
我认为它应该是这样的:
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