开发者

Reload a model attribute

开发者 https://www.devze.com 2023-02-06 05:46 出处:网络
What\'s the best way to refresh a given model attribute? I.e., functionally, I want this: post.body = Post.find(post.id).body

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 *

0

精彩评论

暂无评论...
验证码 换一张
取 消