Overriding id on create in ActiveRecord

后端 未结 13 2638
自闭症患者
自闭症患者 2020-11-28 05:07

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

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

would be ide

13条回答
  •  天命终不由人
    2020-11-28 06:04

    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.

提交回复
热议问题