Overriding id on create in ActiveRecord

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

    Post.create!(:title => "Test") { |t| t.id = 10 }
    

    This doesn't strike me as the sort of thing that you would normally want to do, but it works quite well if you need to populate a table with a fixed set of ids (for example when creating defaults using a rake task) and you want to override auto-incrementing (so that each time you run the task the table is populate with the same ids):

    post_types.each_with_index do |post_type|
      PostType.create!(:name => post_type) { |t| t.id = i + 1 }
    end
    

提交回复
热议问题