Here’s a really simple, but useful ActiveRecord extension I wrote.
1 2 3 4 5 |
|
What this does is reload the current object from the database and returns it. Read more about how this can be useful…
copy this into a file and place it in your project lib directory
What this does is reload the current object from the database and returns it. “Ok, sounds good, where would I use it?”
If I have a User object for example…
1
|
|
and assign some new attributes to it (during an edit for example)
1
|
|
and my template looks like this…
1
|
|
Now if the user blanked out their name (causing an error) and the form gets redisplayed on the update, the name in the header will be blank, which isn’t very nice.
So let’s use our new extension like so…
1
|
|
This will reload the object from the database with the original name in the header.
This looks much cleaner than this I’d say…
1
|
|
Using from_db
does not affect the attributes of the @user value at all, as a seperate object is being returned, so @user can still be used normally in the rest of the code.
from_db
differs from the rails method reload
in that reload
updates the associated objects attributes with those from the database, thus modifying the object. from_db
does not modify the associated objects attributes as it is returning a seperate object instead.
1 2 3 4 |
|
One thing you don’t want to be doing though is appending from_db
to your object all over the place as this will add unnecessary overhead to the database with additional queries. Instead save the from_db value in a seperate variable and use that if you need to use the original values more than once during a request.
P.S. This extension can also be useful in tests for comparing modified values to those currently in the test database. :)