2013-03-15 90 views
1

我目前有一個名爲Image的模型。該模型綁定到ArticleRails中的複合外鍵ActiveRecord

class Article < ActiveRecord::Base 
    has_many: images 
end 

Image表包含article_id,所以圖像與文章相關聯。

但是,我想將我的圖像與其他模型一起使用。因此,我想將article_id更改爲owner_id之類的內容,並向Image模型添加名爲owner_model的新屬性。

這樣,其他模型也可以有很多圖像。

任何想法,如果這是可以實現使用ActiveRecord的優雅和如何去解決它?

在旁註中,我使用CarrierWave處理圖像。

回答

3

您可以使用多態關聯。

rails guide有一個很好的例子可以解決您的問題。

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

class Employee < ActiveRecord::Base 
    has_many :pictures, :as => :imageable 
end 

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