I am importing some data from an old Omnis 7 databse via a text file into Rails. I am using text files for this purpose and am using db:seed to port it in.
In my seeds.rb file I have:
Port.delete_all
File.open("db_ports.txt", "r") do |ports|
ports.read.each_line do |port|
id, name, un_locode, bunker_surcharge, launch_tariff = port.chomp.split("|")
Port.create!(:id => id, :name => name, :un_locode => un_locode, :bunker_surcharge => bunker_surcharge, :launch_tariff => launch_tariff)
end
end
I would like to have the ID number be the one as was assigned in the other database because Berths have a foreign key that looks to Ports and I would need those to match up with each other.
However, when I last imported my data, this didn’t work out as planned and the ID number was not passed in. I’m guessing that I could create empty records which I would then update with the data but was wondering whether this was possible.
You won’t be able to set the id in the
create!call because id is protected from mass assignment in this way. I believe you can set the id by doing something like:You might want to consider having a separate attribute for the id in the old system though (old_omnis_id, maybe). I’ve seen this work successfully in the past. You can then use this attribute to join on in the association or, when you add the berths, you can look up the port’s id in the new system by the old id.