如何在活动记录模型上执行“移动字段”重构

时间:2010-09-22 19:39:24

标签: ruby-on-rails activerecord refactoring migration rails-migrations

这是一个相当普遍的重构,Martin Fowler称之为“移动领域”。鉴于3个型号:

class Person < ActiveRecord::Base
  has_one :contact_details
  has_one :address
end

class ContactDetails < ActiveRecord::Base
end

class Address < ActiveRecord::Base
end

如何重构,包括迁移,从Person到ContactDetails的has_one地址?之后模型看起来像:

class Person < ActiveRecord::Base
  has_one :contact_details
end

class ContactDetails < ActiveRecord::Base
  has_one :address
end

class Address < ActiveRecord::Base
end

1 个答案:

答案 0 :(得分:0)

所以我已经实现了迁移,实际上非常简单,只需要在地址上重命名外键

class MoveAddressFromPersonToContactDetails < ActiveRecord::Migration

  def self.up
    rename_column :addresses, :person_id, :contact_details_id
  end

  def self.down
    rename_column :addresses, :contact_details_id, :person_id
  end

end

所以剩下的就是以某种方式重构代码。