我有一张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'
我如何构建关系以使其有效?