Rails/ActiveRecord, how to prevent pluck from overriding select?

走远了吗. 提交于 2019-12-11 03:46:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!