【发布时间】:2016-10-03 13:13:35
【问题描述】:
我有这个问题:
Client.select("name as dname")
哪个工作正常。
Client.select("name as dname").first.dname
=> "Google"
现在我想将所有 dnames 作为一个数组获取,但 pluck 方法不起作用,因为 dname 不是列名。
2.2.5 :040 > Client.select("name as dname").pluck(:dname)
(0.6ms) SELECT dname FROM "clients"
ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR: column "dname" does not exist
如何获取 dnames 数组? 有没有类似 pluck 的方法适用于使用 as 定义的列名别名。
我能做到
Client.select("name as dname").map{|d| d.dname}
但是循环遍历每条记录对我来说没有任何意义
【问题讨论】:
-
试试这个
Client.select("name as dname").map{|d| d.dname} -
@SantoshSharma 我知道这是可能的,但循环不是最好的解决方案,因为我们已经从数据库中获取了 dname 列表,为什么我们需要再次循环遍历每个结果。?
标签: sql ruby-on-rails postgresql ruby-on-rails-4 activerecord