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 

Need help on your next project or application?

I specialize in Ruby-on-Rails, AngularJS, Javascript, Bootstrap, and Hybrid Mobile Apps with Cordova & Ionic.

Contact Me

Recommended Posts