ActiveRecord的寻找,只返回选定列ActiveRecord

2023-09-08 16:02:22 作者:*xiào擁冷fěnɡ

如果你穿过这个绊倒,检查这两个答案,因为我现在会用勇气此

If you stumble across this, check both answers as I'd now use pluck for this

我有一个相当大的自定义数据集,我想回到被echoe'd出来为JSON。一个部分是:

I have a fairly large custom dataset that I'd like to return to be echoe'd out as json. One part is:

l=Location.find(row.id)
tmp[row.id]=l

但我想要做的是这样的:

but I'd like to do something like:

l=Location.find(row.id).select("name, website, city")
tmp[row.id]=l

但这似乎并不奏效。我将如何得到这个工作?

but this doesn't seem to be working. How would I get this to work?

THX

修改1 另外,有我可以通过只我要包含的属性的数组的方式?

edit 1 alternatively, is there a way that I can pass an array of only the attributes I want included?

推荐答案

L = Location.find(:ID => ID,:选择=>中的名称,网址,城市:限制=> 1)

...或...

L = Location.find_by_sql(:条件=> [?选择名称,网址,城市FROM地点WHERE ID = LIMIT 1,ID])

此引用文档给你选项的完整列表,你可以用 .find ,其中包括如何号码,身份证,或任何其他任意列/约束来限制。

This reference doc gives you the entire list of options you can use with .find, including how to limit by number, id, or any other arbitrary column/constraint.

L = Location.where([ID =?,ID])。选择(名称,网站,城市)。第一个

参考:活动记录查询界面

您也可以交换这些链接调用的顺序,做。选择(...),其中(...)第一个 - 。所有这些调用要做的就是构造SQL查询,然后把它关闭。

You can also swap the order of these chained calls, doing .select(...).where(...).first - all these calls do is construct the SQL query and then send it off.