Ruby-on-rails – Overriding id on create in ActiveRecord

activerecordruby-on-rails

Is there any way of overriding a model's id value on create? Something like:

Post.create(:id => 10, :title => 'Test')

would be ideal, but obviously won't work.

Best Answer

id is just attr_protected, which is why you can't use mass-assignment to set it. However, when setting it manually, it just works:

o = SomeObject.new
o.id = 8888
o.save!
o.reload.id # => 8888

I'm not sure what the original motivation was, but I do this when converting ActiveHash models to ActiveRecord. ActiveHash allows you to use the same belongs_to semantics in ActiveRecord, but instead of having a migration and creating a table, and incurring the overhead of the database on every call, you just store your data in yml files. The foreign keys in the database reference the in-memory ids in the yml.

ActiveHash is great for picklists and small tables that change infrequently and only change by developers. So when going from ActiveHash to ActiveRecord, it's easiest to just keep all of the foreign key references the same.