Rails HABTM具有多态关系

时间:2013-06-24 16:50:35

标签: ruby-on-rails-3 polymorphism has-and-belongs-to-many

我有一张表Category,可以有很多BusinessesPostsBusiness / 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

PostBusiness具有相似的关系。

所以现在当我运行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'

如何构建关系以便这样做?

1 个答案:

答案 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