我认为应该是这样的: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'endclass Categorization belongs_to :category belongs_to :categorizable, polymorphic: trueendclass Business #Post looks the same has_many :categorizations, as: :categorizeable has_many :categories, through: :categorizationsendI 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_relationshipsCategoryRelationship 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 :categoryCategory has these relationships:has_many :category_relationships has_many :businesses, through: :category_relationships has_many :posts, through: :category_relationshipsPost 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 existLINE 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? 解决方案 Similar questions here: Rails polymorphic has_many :throughAnd here: ActiveRecord, has_many :through, and Polymorphic AssociationsI 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'endclass Categorization belongs_to :category belongs_to :categorizable, polymorphic: trueendclass Business #Post looks the same has_many :categorizations, as: :categorizeable has_many :categories, through: :categorizationsend 这篇关于具有多态关系的Rails HABTM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-18 16:32