Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 475
Tom Lehman Avatar asked Jan 21 '11 20:01

Tom Lehman


1 Answers

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 *

like image 86
zetetic Avatar answered Nov 18 '22 07:11

zetetic