2014-09-12 81 views
2

AR声明:在下面的MySQL查询排除ID列从ActiveRecord的结果

Phone.select(:number).distinct.where(in_black_list: true) 

结果:

SELECT DISTINCT number FROM phones WHERE phones.in_black_list = 1 

结果中包含空的标识:

#<ActiveRecord::Relation [ 
    #<Phone id: nil, number: "1234567">, 
    #<Phone id: nil, number: "78567459">, 
    #<Phone id: nil, number: "78567457">, 
    #<Phone id: nil, number: "998567946794567">, 
]> 

如何消除这些ID ?

回答

2

select返回模型对象。您的查询仅指示ActiveRecord将结果限制为仅包含number。你可以从关系中提取你需要的任何数据。例如,如果你想要的号码作为数组,你能做到这一点有:

Phone.select(:number).distinct.where(in_black_list: true).map(&:number) 
# => ["1234567", "78567459", ... ] 

要避免的ActiveRecord创建模型对象,并从MySQL的要求只有一列,用pluck

Phone.distinct.where(in_black_list: true).pluck(:number) 
# => ["1234567", "78567459", ... ]