Overriding id on create in ActiveRecord

后端 未结 13 2556
自闭症患者
自闭症患者 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:11

    Put this create_with_id function at the top of your seeds.rb and then use it to do your object creation where explicit ids are desired.

    def create_with_id(clazz, params)
    obj = clazz.send(:new, params)
    obj.id = params[:id]
    obj.save!
        obj
    end
    

    and use it like this

    create_with_id( Foo, {id:1,name:"My Foo",prop:"My other property"})
    

    instead of using

    Foo.create({id:1,name:"My Foo",prop:"My other property"})

    0 讨论(0)
提交回复
热议问题