oky_sabeni
oky_sabeni

Reputation: 7822

How do I change this query to return an association instead of an array in Rails and Postgres?

Suppose I have this query:

t.pool_tournament_matches
.where(status: "unstarted")
.joins("INNER JOIN pool_tournament_match_users ON pool_tournament_match_users.pool_tournament_match_id = pool_tournament_matches.id")
.joins("INNER JOIN users ON users.id = pool_tournament_match_users.user_id")
.group("pool_tournament_matches.id")
.select("pool_tournament_matches.*, COUNT(users.id) AS user_count")
.select {|m| m.user_count == 2}

The result does return the right matches but it's an array which does not work well with RABL template engine. What converts the query to an array is

.select {|m| m.user_count == 2}` I think.

How would I do this using SQL so that it will return an association and I can chain it further if needed.

I've tried:

t.pool_tournament_matches
.where(status: "unstarted")
.joins("INNER JOIN pool_tournament_match_users ON pool_tournament_match_users.pool_tournament_match_id = pool_tournament_matches.id")
.joins("INNER JOIN users ON users.id = pool_tournament_match_users.user_id")
.group("pool_tournament_matches.id")
.select("pool_tournament_matches.*, COUNT(users.id) = 2)

but it does not work.

Upvotes: 0

Views: 42

Answers (1)

Nikita Misharin
Nikita Misharin

Reputation: 2020

t.pool_tournament_matches
.where(status: "unstarted")
.joins("INNER JOIN pool_tournament_match_users ON pool_tournament_match_users.pool_tournament_match_id = pool_tournament_matches.id")
.joins("INNER JOIN users ON users.id = pool_tournament_match_users.user_id")
.group("pool_tournament_matches.id")
.having("COUNT(users.id) = 2")
.select("pool_tournament_matches.*, COUNT(users.id) AS user_count")

Upvotes: 1

Related Questions