ActiveRecord 查找并仅返回选定的列
编辑2
如果您偶然发现这个问题,请检查两个答案,因为我现在使用 pluck 来实现这一点,
我有一个相当大的自定义数据集,我想将其返回为 json 形式的回显。一部分是:
l=Location.find(row.id)
tmp[row.id]=l
但我想做一些类似的事情:
l=Location.find(row.id).select("name, website, city")
tmp[row.id]=l
但这似乎不起作用。我该如何让它发挥作用?
谢谢
编辑1
或者,有没有一种方法可以传递仅包含我想要包含的属性的数组?
edit 2
If you stumble across this, check both answers as I'd now use pluck for this
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
edit 1
alternatively, is there a way that I can pass an array of only the attributes I want included?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
pluck(column_name)
该方法旨在执行单列选择,作为直接 SQL 查询 返回具有指定列名值的数组 这些值与列具有相同的数据类型。
示例:
请参阅 http://api.rubyonrails.org/classes/ ActiveRecord/Calculations.html#method-i-pluck
它是从 Rails 3.2 开始引入的,并且仅接受单列。在 Rails 4 中,它接受多列
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.
Examples:
see 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
在 Rails 2 中
...或者...
此参考文档为您提供了整个可以与
.find
一起使用的选项列表,包括如何按数字、id 或任何其他任意列/约束进行限制。在 Rails 3 w/ActiveRecord 查询接口
参考: Active Record 查询接口
您还可以交换以下顺序:这些链式调用,执行
.select(...).where(...).first
- 所有这些调用所做的就是构造 SQL 查询,然后将其发送出去。In Rails 2
...or...
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.In Rails 3 w/ActiveRecord Query Interface
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.我的答案很明确,但这就是你可以做的:
顺便说一句,这是 Rails 4
My answer comes quite but this is what you can do:
Btw, this is Rails 4