如何采用" as alias_name"来自rails活动记录查询

时间:2016-10-03 13:13:36

标签: sql ruby-on-rails postgresql ruby-on-rails-4 activerecord

我有这个问题:

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 这样的方法可以使用作为定义的列名别名。

我可以这样做

Client.select("name as dname").map{|d| d.dname}

但循环浏览每条记录对我来说没有任何意义

3 个答案:

答案 0 :(得分:6)

我对拔毛的理解是错误的。从apidock我明白了

  

使用pluck作为快捷方式选择一个或多个属性而不加载一堆记录只是为了获取所需的属性。

所以,

Client.select("name as dname").pluck(:dname)

应该像这样写

Client.pluck("name as dname")

答案 1 :(得分:1)

使用此代码:

Client.select("name as dname").map{|d| d.dname}

答案 2 :(得分:1)

selectpluck不能很好地协同工作,但我使用了一种将别名列连接到查询对象上的解决方法,允许使用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"]