Reputation: 45104
When I to to_sql
on the following query it works fine:
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"
But then when I add pluck
it doesn't work:
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>
Apparently the addition of pluck
changes the type of object from ActiveRecord_Relation
to Array
, and you obviously can't perform to_sql
on an array.
What I'm wanting it to output (for starters) is this:
SELECT tasks.title FROM `tasks` INNER JOIN `recurrences` ON `recurrences`.`id` = `tasks`.`recurrence_id` GROUP BY recurrences.id
...which is in fact what I copy/pasted from the query generated by Task.joins(:recurrence).group('recurrences.id').pluck('tasks.title')
without the to_sql
.
Is it possible to do what I'm wanting to do?
Upvotes: 6
Views: 1683
Reputation: 45104
I figured it out. I have to use 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"
Upvotes: 6