我有这个问题:
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}
但是遍历每条记录对我来说没有任何意义
好吧,我对 pluck 的理解是错误的。从 apidock 我明白了
使用 pluck 作为快捷方式选择一个或多个属性,而无需加载一堆记录只是为了抓取您想要的属性。
所以,
Client.select("name as dname").pluck(:dname)
应该这样写
Client.pluck(:name)
使用此代码:
Client.select("name as dname").map{|d| d.dname}
select
和 pluck
一起玩得不好,但我使用了一种变通方法,将别名列连接到查询对象上,允许采摘。我通常将这样的连接写为以 with_
开头的范围
class Client
scope :with_dname , -> {
# Build a subquery SQL snippet
# Since we will be joining it onto the base table, we need to select the id column as well
subquery = select("name AS dname, #{table_name}.id").to_sql
# join the subquery to base model
joins("JOIN (#{subquery}) as addendum ON addendum.id = #{table_name}.id")
}
end
# this will work
Client.with_dname.first.pluck(:dname) #=> ["Google"]
# this may be more efficient
Client.limit(1).with_dname.first.pluck(:dname) #=> ["Google"]