Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails Query: Joining tables and selecting multiple columns

There are two models: microposts and users

"microposts" contains 4 columns: name, type, user_id and id

"users" contains 4 columns: name, type, address and id

Microposts belongs to users; users contains many microposts.

I want to find how many microposts each user has but for some reason, I cannot get the query to work properly.

The query I tried is:

User.joins(:microposts).group("users.id").select("users.*, count(microposts.id) as postcount")

This only pulls the attributes from the users table, but excludes the columns from the micropost table and also excludes the count column i created.

For some reason,

User.joins(:microposts).group("users.id").count

works but it only returns the user.id along with the count. I want to pull the other columns as well.

I also tried using "includes" instead of "joins", but that just returns all the columns of the users table and none from the microposts table.

User.includes(:microposts).group("users.id").select("users.*, count(microposts.id) as postcount")

Can anyone help? Thanks!

like image 702
user3575214 Avatar asked Dec 21 '25 12:12

user3575214


1 Answers

You need both joins and includes, I think.

User.joins(:microposts).
  includes(:microposts).
  group("users.id").
  select("users.*, count(microposts.id) as postcount")
like image 167
Grant Birchmeier Avatar answered Dec 23 '25 04:12

Grant Birchmeier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!