Today I Learned

hashrocket A Hashrocket project

Rails restore_attributes

Today I found a useful method in ActiveRecord, restore_attributes.

This method restores attributes on a dirty model. Use it when you are hacking in the Rails console and want to quickly return to a clean slate.

Dirty the record:

pry> p = Post.first
=> #<Post:0x007f8462b09eb8
 id: 106,
 created_at: Sun, 09 Feb 2014 17:15:01 CST -06:00,
 url_slug: "hello-world">

pry> p.url_slug = 'foobar'
=> "foobar"

pry> p.created_at = Time.now
=> 2015-10-13 11:41:37 -0500

pry> p
=> #<Post:0x007f8462b09eb8
 id: 106,
 created_at: Tue, 13 Oct 2015 11:41:37 CDT -05:00,
 url_slug: "foobar">

And restore:

pry> p.restore_attributes
=> ["url_slug", "created_at"]

pry> p
=> #<Post:0x007f8462b09eb8
 id: 106,
 created_at: Sun, 09 Feb 2014 17:15:01 CST -06:00,
 url_slug: "hello-world">

https://github.com/rails/rails/blob/master/activemodel/lib/active_model/dirty.rb#L191

See More #rails TILs
Looking for help? Hashrocket has been an industry leader in Ruby on Rails since 2008. Rails is a core skill for each developer at Hashrocket, and we'd love to take a look at your project. Contact us and find out how we can help you.