当我在以下查询中2.1.8 :017 > Task.joins(:recurrence).group('recurrences.id').to_sql
=> "SELECT `tasks`.* FROM `tasks` INNER JOIN `recurrences` ON `recurrences`.`id` = `tasks`.`recurrence_id` GROUP BY recurrences.id"
时,它可以正常工作:
pluck
但是当我添加2.1.8 :018 > Task.joins(:recurrence).group('recurrences.id').pluck('tasks.title').to_sql
(21.0ms) SELECT tasks.title FROM `tasks` INNER JOIN `recurrences` ON `recurrences`.`id` = `tasks`.`recurrence_id` GROUP BY recurrences.id
NoMethodError: undefined method `to_sql' for #<Array:0x007fbde9863f18>
时,它不起作用:
pluck
显然,添加ActiveRecord_Relation
会将对象类型从Array
更改为to_sql
,您显然无法对数组执行SELECT tasks.title FROM `tasks` INNER JOIN `recurrences` ON `recurrences`.`id` = `tasks`.`recurrence_id` GROUP BY recurrences.id
。
我想要它输出(对于初学者)是这样的:
Task.joins(:recurrence).group('recurrences.id').pluck('tasks.title')
...这实际上是我在没有to_sql
的情况下从n
生成的查询中复制/粘贴的内容。
有可能做我想做的事吗?
答案 0 :(得分:2)
我明白了。我必须使用select
。
> Task.select('tasks.title').joins(:recurrence).group('recurrences.id').to_sql
=> "SELECT tasks.title FROM `tasks` INNER JOIN `recurrences` ON `recurrences`.`id` = `tasks`.`recurrence_id` GROUP BY recurrences.id"