Tomek Wejchorowski Tomek Wejchorowski - 3 months ago 9
SQL Question

Transform SQL query to ActiveRecord Query

Issue:
I don't know how to convert this PostgreSQL query:

select news_id, sum(case when likes.like then 1 else -1 end) as max_positive from likes group by(news_id) order by(max_positive) desc


to ActiveRecord Query.

What I tried:

Like.group(:news_id)
.sum('CASE WHEN likes.like THEN 1 ELSE -1 end')
.max_by { |_k, v| v }


But result is array and not select news_id.

Answer

Like this?

Like.group(:news_id).select("news_id, SUM(case when likes.like then 1 else -1 end) as max_positive").order("max_positive desc")