Overwrite primary key when importing with ActiveRecord

In my migrations I am importing data from a CSV file.

So i first create the table :

create_table :customers do |t|

and then import data from a CSV into it. The CSV data allready contains
values for the id field. My problem is that activerecord won't let me
override the id field :

Customer.create(:id=>1000, :name=>.........)

It uses its own ID.

Does anyone know how I can solve this the correct way?

Any help is appreciated.


customer = Customer.new(:name => ...) do |c|
   c.id = 1000

You can't set the id from the hash, but you can set it separately.


Rob Biedenharn http://agileconsultingllc.com

Thanks Rob, you've saved me writing some ugly code to get around it.

What's the rational behind that behavior?


Well, you normally expect the :id to be auto-assigned by the database so it is prohibited (ignored) in the hash. Consider something like:

fred = Customer.find_by_name('fred')
barney = Customer.new(fred.attributes)

As long as there are no other uniqueness constraints, barney should be saved and have his own id.

You can use attr_protected to pass this behavior to other columns of your choosing.