4

我有一张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'

我如何构建关系以使其有效?

4

1 回答 1

13

类似的问题在这里:Rails polymorphic has_many :through 在这里:ActiveRecord、has_many :through 和 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
于 2013-06-24T17:15:07.983 回答