rails:将关系更改为多态

时间:2015-12-02 16:57:01

标签: ruby-on-rails ruby

让我们对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添加能够获得图像的功能;
我需要进行哪种迁移才能确保现有的迁移 产品&#39;图像被保留,关系现在是多态的,如此 -

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

1 个答案:

答案 0 :(得分:0)

class AddImageableIdAndTypeToPictures < ActiveRecord::Migration
  def up
    add_column :pictures, :imageable_type, :string
    add_column :pictures, :imageable_id, :integer

    Picture.all.each do |picture| 
      picture.imageable_type = 'Product'
      picture.imageable_id = picture.product_id
      picture.save
    end
  end
end