I need help in converting this SQL to ActiveRecord query.
SELECT
MAX(total_sales.start_date) AS maximum_start_date,
customers.external_id, product_categories.external_id AS product_category_id
FROM
total_sales
INNER JOIN
customers
ON
customers.id = total_sales.customer_id
LEFT JOIN
product_categories
ON
product_categories.id = total_sales.product_category_id
WHERE
(customers.organization_id = 1)
GROUP BY
customers.external_id,
product_categories.external_id
I tried doing
TotalSales.joins(:customer).includes(:product_category).
where("customers.organization_id = ?", 1).
group("customers.external_id, product_categories.external_id").
maximum(:start_date)
and it generates almost the query I want. This is what it generates:
SELECT
MAX("total_sales"."start_date") AS maximum_start_date,
customers.external_id, product_categories.external_id AS customers_external_id_product_categories_external_id
FROM
"total_sales"
INNER JOIN "customers" ON
"customers"."id" = "total_sales"."customer_id"
LEFT OUTER JOIN "product_categories" ON
"product_categories"."id" = "total_sales"."product_category_id"
WHERE
(customers.organization_id = 1)
GROUP BY
customers.external_id, product_categories.external_id
But this returns on Rails:
=> {"DIA"=>Wed, 01 Jan 2014, "MES"=>Wed, 01 Jan 2014, nil=>Wed, 01 Jan 2014}
If I run that query on DB console, it returns
"2014-01-01";"CLIENTE.1";"DIA"
"2014-01-01";"CLIENTE.1";"MES"
"2014-01-01";"CLIENTE.1";""
"2014-01-01";"CLIENTE.10";"DIA"
"2014-01-01";"CLIENTE.10";"MES"
"2014-01-01";"CLIENTE.10";""
"2014-01-01";"CLIENTE.100";"DIA"
"2014-01-01";"CLIENTE.100";"MES"
...
and this is what I want. On DB console it works, but on Rails it doesn't. :(