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|

end

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.

Thanks
Chris

On Feb 26, 2008, at 8:31 AM, Chris R. wrote:

values for the id field. My problem is that activerecord won’t let me
Thanks
Chris

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

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

-Rob

Rob B. http://agileconsultingllc.com
[email protected]

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

What’s the rational behind that behavior?

Chris

On Feb 26, 2008, at 8:31 AM, Chris R. wrote:

values for the id field. My problem is that activerecord won’t let me
Thanks
Chris

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

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

-Rob

Rob B. http://agileconsultingllc.com
[email protected]

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)
barney.save

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.

-Rob