当涉及pluck时,to_sql不起作用

时间:2016-09-30 19:09:34

标签: ruby-on-rails activerecord

当我在以下查询中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生成的查询中复制/粘贴的内容。

有可能做我想做的事吗?

1 个答案:

答案 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"