2013-06-24 109 views
3

我有一個表Category,它可以有許多BusinessesPosts。而一個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' 

如何組織的關係,所以這個工作?這裏

+0

可能的複製[ActiveRecord的,有\ _many:通過和多態關聯( http://stackoverflow.com/questions/1683265/activerecord-has-many-through-and-polymorphic-associations) – sbonami

回答

9

類似的問題: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 
+0

只是好奇...爲什麼我們需要的「has_many:企業,通過::分類.... 「和」has_many:帖子,通過:: categorizations ...「類別模型?爲什麼我們不能只擁有「has_many:分類」? –

+0

@RavJohal我還沒有測試過這個,但我的想法是,你實際上不必在Category類中有最後兩個'has_many'行,但你可能需要它們。所有最後兩行代碼都是按照我的理解,它是在Category類中創建輔助方法,並允許您執行諸如「@ category.businesses」或者「@ category.posts.where(published:true)'等等。如果沒有最後兩個has_many語句,你將不會有這些幫助器方法,並且必須做這樣的事情:'@ category.categorizations.where(categorizable_type:'Post')......',基本上更難。 – FireDragon