2012-03-28 25 views
1

假設我有一個Company模型和一個Product模型,這兩個模型都有一個UserUploadedImage與它們相關聯。我想創建我的UserUploadedImage,以便我可以編寫image.parent,並且將引用ProductCompany(在這種情況下以適用者爲準)。配置我的模型,以便一個字段可以引用許多不同類型的類

我知道我可以在UserUploadedImage的第二列中存儲ProductCompany,並有條件查找適當的值。但是,我不確定放置這些代碼的最佳位置,或者是否有更簡單的方法來實現我的目標。謝謝!

回答

3

你需要看看什麼是協會多態關聯

http://guides.rubyonrails.org/association_basics.html#polymorphic-associations

多態關聯

一個更高級的扭曲是多態的關聯。通過多態關聯,一個模型可以屬於一個以上的其他模型。例如,您可能有一個屬於員工模型或產品模型的圖片模型。

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 

您可以將多態的belongs_to聲明視爲設置任何其他模型可以使用的接口。從員工模型的實例中,您可以檢索一組圖片:@ employee.pictures

同樣,您可以檢索@ product.pictures

如果你有圖片模型的實例,您可以通過到達其 @ picture.imageable。爲了使這項工作,你需要同時聲明一個外鍵列,並在模型聲明多態性接口類型列:

class CreatePictures < ActiveRecord::Migration 
    def change 
    create_table :pictures do |t| 
     t.string :name 
     t.integer :imageable_id 
     t.string :imageable_type 
     t.timestamps 
    end 
    end 
end 

這種遷移可以通過使用t.references形式進行簡化:

class CreatePictures < ActiveRecord::Migration 
    def change 
    create_table :pictures do |t| 
     t.string :name 
     t.references :imageable, :polymorphic => true 
     t.timestamps 
    end 
    end 
end 
相關問題