简体   繁体   中英

RAILS: How to select fields from associated table with grouping and create a hash from result?

I would like to create an active record query and store the result in a hash which includes summary information from associated tables as follows.

Here is the tables and associations:

Post belongs_to: category
Category has_many: posts

Here I would like to count the # of posts in each category and create a summary table as follows (with the SQL query for the desired table):

select c.name, count(p.id) from posts a left join categories c on p.category_id = c.id where p.status = 'Approved' group by (c.name) order by (c.name);

    Category   | count 
---------------+-------
 Basketball    |     2
 Football      |     3
 Hockey        |     4

(3 rows)

Lastly I would like to store the result in a hash as follows:

summary_hash = { 'Basketball' => 2, 'Football' => 3, 'Hockey' => 4 }

I will appreciate if you can guide me how to write the active record query and store the result in the hash.

Try

Post.where(status: 'Approved').joins(:category).
  select("categories.name").group("categories.name").count

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM