配置我的模型,以便字段可以引用许多不同类型的类

时间:2012-03-28 21:04:08

标签: ruby-on-rails ruby-on-rails-3 activerecord

假设我有一个Company模型和一个Product模型,这两个模型都与UserUploadedImage相关联。我希望以某种方式创建我的UserUploadedImage,以便我可以编写image.parent并引用ProductCompany,以适用于该情况。

我意识到我可以在UserUploadedImage中使用ProductCompany存储第二列,并且有条件查找适当的值。但是,我不确定放置此代码的最佳位置,或者是否有更清晰的方法来实现我的目标。谢谢!

1 个答案:

答案 0 :(得分: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模型的实例中,您可以检索图片集合: @ 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