Tom Lehman
Tom Lehman

Reputation: 89373

Reload a model attribute

What's the best way to refresh a given model attribute?

I.e., functionally, I want this:

post.body = Post.find(post.id).body

with a nicer syntax. Maybe

post.reload_body!

Edit: I only want to reload a single attribute (not all attributes at once)

Upvotes: 13

Views: 7972

Answers (1)

zetetic
zetetic

Reputation: 47588

Beats me why you'd want to do such a thing, but:

def reload_attribute(attr)
  value = self.class.where(:id=>id).select(attr).first[attr]
  self[attr] = value
end

This issues a SELECT that retrieves just the one column and assigns its value to the attribute in the current model instance. Call with (eg):

post = Post.find(1)
post.reload_attribute(:body)

Really though, you should just go with post.reload (doc). Unless you have hugely wide columns that impose some performance cost on doing SELECT *

Upvotes: 11

Related Questions