Changing existing has_many to polymorphic relationship in Rails 3

I have an existing has_many relationship between two models - call them "cars" and "passengers" - with several thousand passengers belonging to several hundred cards in my production environment. I add another model, call it “trains”, and I want to change the existing has_many relationship between cars and passengers to polymorphic, linking each passenger with a car or train.

What should my migration look like? I want to preserve the existing relationships in my database during migration, so I would rather rename the table, instead of dropping one column to replace it with another. In addition, I want to be able to do this without opening the server console and manually editing all the records, so I can simply transfer the entire database in one fell swoop when I push my changes to production. Any suggestions?

TL DR: How to change the existing has_many relation to polymorphic with the new model?

+5
source share
1 answer

You will need to write some migrations, for example

  • Add two columns to the Passenger table. -> rails g migration change_column_in_passenger

:

def up
  rename_column :passengers, :car_id, :transport_id
  add_column :passengers, :transport_type, :string
  Passenger.reset_column_information
  Passenger.update_all(:transport_type => "Car")
end

def down
  rename_column :passengers, :transport_id, :car_id
  remove_column :passengers, :transport_type
end



 , Car Passenger.   Passenger.

+23

All Articles