Home>

I am making a web application with rails.
I encountered an N + 1 problem and started using includes.
I asked a question without knowing the following method.

  • There are two models, Group and User
  • User belongs to any one group (associated)
  • Read both tables as Group.includes (: user)
  • At this time, the child table user wants to read only males
  • I want to read both parent tables
Group model
id name
1 Group A
2 Group B
User model
id name Group id Gender
1 Taro 1 Men
2 Hanako 2 woman
3 Jiro 1 Men
Error message

If i search, you will see that the child table is used to narrow down the parent table.
I couldn't find a way to narrow down only the child table without narrowing down the parent table.
(Did you find it?)
If i execute the following, only GroupA can be extracted, and the parent table Group wants to output both A and B.

Applicable source code

※ Simplified

Rails
## controller
@groups = Group.includes (: users) .where (gender: male) .references (: users)
## view
@ groups.each do | group |
  group.name
end
I tried to try

scope etc. but it didn't work and I would appreciate your advice.

Supplemental information (FW/tool version etc.)

The Rails version is 5.2.2.
DB is developed with mySQL, cloud9.

  • Answer # 1

    Only child records specified by specifying a join condition can be joined.

    Group.eager_load (: users) .joins ("AND users.gender = male")


    eager_loadcan beincludes, but
    I think it would have been better to useeager_loadwhen it is always combined.

Related articles