问题
As an example, I want to run a query like
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
How do I make rails/activerecord to handle pluck on the result of the select query rather than overriding it?
回答1:
It's not possible. pluck will always override any select you specify. But you can do this:
people = Person.where(last: "smith").group(:age).order(:age)
people.pluck("GROUP_CONCAT(`first` SEPARATOR ', ')")
or this:
people = Person.select("GROUP_CONCAT(`first` SEPARATOR ', ') as names") \
.where(last: "smith").group(:age).order(:age)
people.all.collect(&:name)
来源:https://stackoverflow.com/questions/19918246/rails-activerecord-how-to-prevent-pluck-from-overriding-select