Manually Set The ID Of A Record When Creating Or Seeding In Rails

Posted by Weston Ganger on November 29, 2015

I’ve needed to make a new record have a specific ID in the past. This was an issue becuase ID is attr_protected.

We have two ways we can do this. But I recommend the Method 1 because it only uses one database call and won’t auto-increment the id column in the table.

# Method 1
post = Post.new({content: "my post content"})
post.id = 10

# Method 2
Post.create({content: "my post content"}){|post| post.id = 10}

Related External Links:

Posted in Rails and Tagged with rails active-record 

Want me to help develop your next project or application?

Contact Us

Specializing in Ruby-on-Rails, Javascript, Multi-Platform Electron Desktop Apps and Hybrid Cordova Mobile Apps.

Recommended Posts