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)
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 *
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With