Search code examples
ruby-on-railsrubyactiverecordruby-on-rails-2

Is there a built-in way to fetch a single ActiveRecord attribute from the database (ignoring the in-memory value)?


Big caveat: we're using Rails 2 at my company. So I'm looking for an answer (if one exists) from ActiveRecord 2.

Is there a method already included in ActiveRecord to fetch the most up-to-date value of an attribute from the database, without calling reload or overwriting the current in-memory value?

For example:

p = Person.find(123)

# Now the in-memory value is "Joe", which would be overwritten
# if I called reload
p.nickname = "Joe"

# I want something like this to execute the equivalent of:
# SELECT 'nickname' FROM persons WHERE id = 123;
nickname_from_db = p.get_current_value(:nickname)

I realize what I'm asking would be very simple to implement myself; I just don't want to reinvent the wheel if there's already an ActiveRecord method that does what I'm asking.


Solution

  • You can use the select option.

    Person.find(123, :select => "nickname")