刷新一个模型属性 [英] 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!
编辑:我只想重新加载的单的属性(不是所有属性的一次)
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
这发出 SELECT
检索只是一列,它的值赋给当前模型实例的属性。与调用(比如):
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)
真的不过,你应该去与 post.reload
( DOC )。除非你有非常宽列强加一些性能成本做 SELECT *
Really though, you should just go with post.reload
(doc). Unless you have hugely wide columns that impose some performance cost on doing SELECT *
这篇关于刷新一个模型属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!