2012-11-19 72 views
1

我需要在用戶,產品和照片模型之間創建關係。用戶可以將照片添加到產品。因此,用戶has_many照片和產品has_many照片,但每張照片belongs_to都是產品和用戶。我如何在Rails中實現這一點?據我所知,多態關聯只能讓照片屬於產品或用戶。我是否必須爲用戶照片和產品照片關係使用單獨的has_many_through關係?多態關聯和/或has_many_through

回答

2

在同一模型中可以有多個belongs_to屬性。實質上,標記爲belongs_to的模型將持有已用has_many標記的模型的外鍵。

class MyModel < ActiveRecord::Base 

    belongs_to :other_model1 
    belongs_to :other_model2 

end 

如果你想簡單地通過增加的has_many使用多態的同事爲你所提到的下面你可以做到這一點沿着這些線路

class Photos < ActiveRecord::Base 
    belongs_to :imageable, :polymorphic => true 
end 

class Users < ActiveRecord::Base 
    has_many :photos, :as => :imageable 
end 

class Product < ActiveRecord::Base 
    has_many :photos, :as => :imageable 
end 

在這種情況下,你可以創建關係:phots,:如=>:無需重新訪問Photos類的可成像屬性。

+0

謝謝,這清除了我的困惑。 – graphmeter