0
讓我們多態關係的例子稍微複雜的情況下,在the docs(2.9)
假設看出,最初,只有Product
可以有一個Image
;我們必須像這個 -軌道:改變的關係是多態
class Picture < ActiveRecord::Base
belongs_to :product
end
class Employee < ActiveRecord::Base
# nothing yet
end
class Product < ActiveRecord::Base
has_many :pictures
end
一段時間後,我們要添加一個Employee
有一個形象也的能力;
什麼樣的遷移做我需要運行,以確保現有 產品圖像的保存和關係現在是多態的,像所謂
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
你只需要添加兩列' imageable_id和imageable_type'並運行命令'Picture.all.each do | picture | picture.imageable_type ='產品'; picture.imageable_id = picture.product_id; picture.save end'你可以在你的遷移中自己寫這個。 –
之後,你可以運行遷移從'圖片'表中刪除'product_id'列 –
@PardeepDhingra我看到你昨天發佈了這個答案,但它今天已經消失;你能否再次發表,因爲這似乎是我能接受的一個好答案? –