我有一個表Category
,它可以有許多Businesses
和Posts
。而一個Business
/Post
可以有很多Categories
,所以我創建了一個叫做CategoryRelationship
的多態表格來分解多對多的關係。Rails具有多態關係的HABTM
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
將有類似的relati在船上作爲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'
如何組織的關係,所以這個工作?這裏
可能的複製[ActiveRecord的,有\ _many:通過和多態關聯( http://stackoverflow.com/questions/1683265/activerecord-has-many-through-and-polymorphic-associations) – sbonami