Skip to content

Instantly share code, notes, and snippets.

@hisapy
Created April 15, 2013 18:26
Show Gist options
  • Save hisapy/5390206 to your computer and use it in GitHub Desktop.
Save hisapy/5390206 to your computer and use it in GitHub Desktop.
Rails ActiveRecord .select() not working with .joins() and .count()
# Given the following
ExitPoll.select('listas.id, numero, listas.nombre, listas.color')
.joins(:chapa_presidencial)
.count(group: :chapa_presidencial)
# Rails executes the following 2 SQL queries
SELECT COUNT(*) AS count_all, chapa_presidencial_id AS chapa_presidencial_id
FROM `exit_polls` INNER JOIN `listas` ON `listas`.`id` = `exit_polls`.`chapa_presidencial_id`
GROUP BY chapa_presidencial_id
SELECT `listas`.* FROM `listas` WHERE `listas`.`id` IN (1, 2, 3, 7, 8, 9)
# I need the last query to be
SELECT `listas`.`id`, `listas`.`numero`, `listas`.`nombre`, `listas`.`color` FROM `listas` WHERE `listas`.`id` IN (1, 2, 3, 7, 8, 9)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment