K
K
Kana2016-01-22 20:59:52
Ruby on Rails
Kana, 2016-01-22 20:59:52

How to add a column from the second table to the first table using the index from the first?

I have 3 tables.

titles {id, name}
users {id}
votes {user_id, title_id}

At the moment I can do this Vote.group(:title_id).countto get the number of votes (votes) for each title (titles). But the result is like this
{33=>2, 34=>1, 36=>1, 38=>3, 39=>2, 40=>4, 41=>3, 42=>2, 43=>3, 44=>3, 45=>1, 46=>4, 47=>5, 48=>4, 49=>3, 50=>3, 52=>2, 62=>1}
, and I need to substitute the name (titles.name) instead of id.
Given code
Vote.includes(:title).group("votes.title_id").count
works exactly the same as the option above, but this one doesn't want to work anymore Vote.includes(:title).group("titles.name").count. Using joins instead of includes doesn't help.
How can I get the output{"name" => count}?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
vsuhachev, 2016-01-23
@kana-desu

Your code works fine for me:

Vote.joins(:title).group("titles.id, titles.name").count

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question