2012-11-19 69 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