Rails的:负载只有一个属性,而不是整个模型 [英] Rails: Load just one attribute not a whole model

查看:83
本文介绍了Rails的:负载只有一个属性,而不是整个模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以说我有一个模型,,这是大,有很多组件。对于一个给定的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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆