你需要看看什么是协会多态关联
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