Ruby-on-rails ActiveRecord 查找并只返回选定的列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7911014/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ActiveRecord find and only return selected columns
提问by timpone
edit 2
编辑 2
If you stumble across this, check both answers as I'd now use pluck for this
如果您偶然发现了这一点,请检查这两个答案,因为我现在会为此使用 pluck
I have a fairly large custom dataset that I'd like to return to be echoe'd out as json. One part is:
我有一个相当大的自定义数据集,我想将其返回为 json。一部分是:
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
谢谢
edit 1
alternatively, is there a way that I can pass an array of only the attributes I want included?
或者,编辑 1,有没有一种方法可以传递一个只包含我想要包含的属性的数组?
采纳答案by jefflunt
In Rails 2
在 Rails 2
l = Location.find(:id => id, :select => "name, website, city", :limit => 1)
...or...
...或者...
l = Location.find_by_sql(:conditions => ["SELECT name, website, city FROM locations WHERE id = ? LIMIT 1", id])
This reference docgives you the entire list of options you can use with .find, including how to limit by number, id, or any other arbitrary column/constraint.
此参考文档为您提供了可以与 一起使用的完整选项列表.find,包括如何按数字、ID 或任何其他任意列/约束进行限制。
In Rails 3 w/ActiveRecord Query Interface
在带有 ActiveRecord 查询接口的 Rails 3 中
l = Location.where(["id = ?", id]).select("name, website, city").first
Ref: Active Record Query Interface
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.
您还可以交换这些链接调用的顺序,这样做.select(...).where(...).first- 所有这些调用都是构造 SQL 查询,然后将其发送出去。
回答by prasad.surase
pluck(column_name)
采摘(列名称)
This method is designed to perform select by a single column as direct SQL query Returns Array with values of the specified column name The values has same data type as column.
此方法旨在通过单个列执行选择作为直接 SQL 查询返回具有指定列名值的数组 值与列具有相同的数据类型。
Examples:
例子:
Person.pluck(:id) # SELECT people.id FROM people
Person.uniq.pluck(:role) # SELECT DISTINCT role FROM people
Person.where(:confirmed => true).limit(5).pluck(:id)
see http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-pluck
见http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-pluck
Its introduced rails 3.2 onwards and accepts only single column. In rails 4, it accepts multiple columns
它从 3.2 开始引入 Rails,并且只接受单列。在 rails 4 中,它接受多列
回答by tkhuynh
My answer comes quite late because I'm a pretty new developer. This is what you can do:
我的回答来得很晚,因为我是一个相当新的开发人员。这是你可以做的:
Location.select(:name, :website, :city).find(row.id)
Btw, this is Rails 4
顺便说一句,这是Rails 4

