Rails的:负载只有一个属性,而不是整个模型 [英] Rails: Load just one attribute not a whole model
问题描述
可以说我有一个模型,富
,这是大,有很多组件。对于一个给定的Ajax查询,我只关心在一个特定的属性,栏
,这是在FOOS表中的列。
Lets say I have a model, Foo
, which is big and has lots of components. For a given Ajax query I'm only interested in one particular attribute, bar
, which is a column in the foos table.
有一个简单的方法,我可以加载只是属性,而不是打扰检索记录的休息吗?举例来说,如果所有我想知道的是富了吧ID为#的 _ 的_,我怎么能检索?
Is there a simple way I could load just that attribute, and not bother with retrieving the rest of the record? For instance if all I want to know is the bar for Foo with id#__, how could I retrieve that?
推荐答案
您可以通过调用只返回特定的列选择
方法,包含您需要的属性为字符串返回。对于您的例子:
You can return only specific columns by calling the select
method with a string containing the attributes you want to return. For your example:
Foo.select('bar').first #<Foo bar: 1>
请注意,这些物体会像正常的ActiveRecord的对象,但返回零
您没有选择任何领域,因此使用此功能要小心。
Keep in mind that these objects will act like normal ActiveRecord objects but return nil
for any field you did not select, so take care using this functionality.
您可以拨打选择在类名本身或任何关联,这样你就可以连续使用ActiveRecord的调用您通常使用像其中,
等。
You can call select on the class name itself or any Relation, so you can chain together the ActiveRecord calls you usually use like where
, etc.
这篇关于Rails的:负载只有一个属性,而不是整个模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!