Rails / ActiveRecord,如何防止覆盖select?

时间:2013-11-11 23:44:54

标签: ruby-on-rails ruby activerecord

举个例子,我想运行像

这样的查询
people = Person.select("GROUP_CONCAT(`first` SEPARATOR ', ') as names") \
.where(last: "smith").group(:age).order(:age)

# which basically gives me something like
# SELECT GROUP_CONCAT(`first` SEPARATOR ', ') as names ...

#####################

# but when I add pluck
people.pluck(:names)
# it does
# SELECT names ...
# and gives me an Unknown column error

如何使用rails / activerecord来处理选择查询的结果而不是覆盖它?

1 个答案:

答案 0 :(得分:3)

这是不可能的。 pluck将始终覆盖您指定的任何选择。但你可以这样做:

people = Person.where(last: "smith").group(:age).order(:age)
people.pluck("GROUP_CONCAT(`first` SEPARATOR ', ')")

或者这个:

people = Person.select("GROUP_CONCAT(`first` SEPARATOR ', ') as names") \
.where(last: "smith").group(:age).order(:age)
people.all.collect(&:name)