2016-10-03 27 views
3

采摘“为ALIAS_NAME”有这个疑问:我如何从轨活动记录查询

Client.select("name as dname") 

这是工作的罚款。

Client.select("name as dname").first.dname 
=> "Google" 

现在我想所有dnames作为一个数组,但采摘方法不起作用为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 

如何获取dname数组? 是否有像pluck这样的方法处理列名别名,其使用定义为

我能做到这一点

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

但通过每个记录循环不作出任何意义,我

+1

试试这个Client.select(“name as dname”)。 d.dname}' –

+0

@SantoshSharma我知道这是可能的,但循环并不是最好的解决方案,因为我们已经从数据库中获得dname列表,为什么我们需要再次循环每个结果。? – dnsh

回答

3

那么我的勇气的理解是错误的。从apidock我明白

使用pluck作为选择一个或多个属性的快捷方式,不加载一堆记录只是为了抓取你想要的属性。

所以,

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

应该这样写

Client.pluck("name as dname") 
2

使用此代码:

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

selectpluck不玩好起来,但我已经使用加入了别名的列到一个解决方法查询对象,允许采摘。我通常写这样的连接作为范围从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"]