views:

17

answers:

1

This is a fairly common refactoring, Martin Fowler calls it 'move field'. Given 3 models:

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

class ContactDetails < ActiveRecord::Base
end

class Address < ActiveRecord::Base
end

how do I refactor, including migration, the has_one address from Person to ContactDetails? Afterwards the models would look like:

class Person < ActiveRecord::Base
  has_one :contact_details
end

class ContactDetails < ActiveRecord::Base
  has_one :address
end

class Address < ActiveRecord::Base
end
A: 

So I've got as far as the migration, pretty simple actually, just need to rename the foreign key on addresses

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

so all that's left is to refactor the code, somehow.

opsb