Rails / ActiveRecord,如何防止摘录覆盖选择? [英] Rails/ActiveRecord, how to prevent pluck from overriding select?

查看:60
本文介绍了Rails / ActiveRecord,如何防止摘录覆盖选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我想运行一个查询

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

我如何使rails / activerecord处理选择结果的选择

How do I make rails/activerecord to handle pluck on the result of the select query rather than overriding it?

推荐答案

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

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 ', ')")

或这样:

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

这篇关于Rails / ActiveRecord,如何防止摘录覆盖选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆