你需要看看什麼是協會多態關聯
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