简体   繁体   中英

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!

You need both joins and includes , I think.

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

How do you intend to use it?

If you want to loop over users and display both user attributes and it's microposts you can simply do this:

<% @users.each do |user| %>
  <%= user.microposts.size %>
  <%= other_user_attributes %>

  <%= user.microposts.each do |micropost| %>
    <%= micropost_attributes %>
  <% end %>
<% end %>

Ps If you also want micropost attributes returned you can do so in your select query. If you add 'microposts.title as micropost_title' it will return the micropost title as well. However, that makes no sense if you group based on the user id since one user can have multiple microposts.

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