1

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.

1 Answer 1

2

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")
Sign up to request clarification or add additional context in comments.

3 Comments

it's not all good. Your query correct select id, but not sum. ` #<ActiveRecord::Relation [#<Like id: nil, news_id: 53>, #<Like id: nil, news_id: 46>, #<Like id: nil, news_id: 58>...`
@TomekWejchorowski: It is there but the model class's inspect doesn't know it (stackoverflow.com/a/38270375/479863), just ask for it by calling the max_positive method on the returned model instances. See stackoverflow.com/a/24131675/479863, stackoverflow.com/a/27494947/479863, stackoverflow.com/a/18351188/479863, stackoverflow.com/a/17714928/479863, ...
Thank you very much @lusketeer. Great links!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.