Redline Software Inc. - Winnipeg's Leader in Ruby on Rails Development

From_db ActiveRecord Extension

Here’s a really simple, but useful ActiveRecord extension I wrote.

1
2
3
4
5
class ActiveRecord::Base
  def from_db
    self.class.find self.id
  end
end

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
@user = User.find :first

and assign some new attributes to it (during an edit for example)

1
@user.attributes = params[:user]

and my template looks like this…

1
<h1>Editing <%= @user.name %></h1>

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
<h1>Editing <%= @user.from_db.name %></h1>

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
<h1>Editing <%= User.find(@user.id).name %></h1>

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
# @user is updated with the original attributes from the database
@user.reload
# @user is not modified as it returns a new object with the original attributes from the database
db_user = @user.from_db

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. :)

Comments