2012-03-28 45 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 
相关问题