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
id | name |
---|---|
1 | Group A |
2 | Group B |
id | name | Group id | Gender |
---|---|---|---|
1 | Taro | 1 | Men |
2 | Hanako | 2 | woman |
3 | Jiro | 1 | Men |
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.
※ Simplified
Rails
## controller
@groups = Group.includes (: users) .where (gender: male) .references (: users)
## view
@ groups.each do | group |
group.name
end
I tried to tryscope 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
Related articles
- ruby on rails - i want to remove the character limit (40 characters) for line message api link labels
- ruby on rails - cannot save nested child model
- ruby - i want to collect the same records using rails group and get the value
- ruby on rails 5 - child model record not created
- in ruby on rails, i want to limit it to information other than foreign key constraint in references
- ruby on rails - mvc rails
- ruby on rails 6 - i changed the project name of rails, but it became inaccessible
- ruby on rails - i want to jump to the action of another controller with render
- ruby on rails - heroku: how to check the database_url used for regular backup
- ruby on rails 5 - i want to update the received parameters with nil
- ruby on rails - it is not saved in the database after registering the product
- ruby - rails tutorial chapter 2 (6th edition)
- ruby on rails - rails6 rspec model run-time error nomethoderror: undefined method `valid?'for nil: nilclass
- ruby on rails 6 - rails6 activerecord :: recordinvalid in userscontroller # update
- ruby on rails - saved description in nested controller
- ruby on rails - cart function routing error cannot be resolved
- ruby on rails - rails s can't
- ruby on rails - how to transition from the top page
- ruby on rails - i want to implement a function for administrator users to register luggage for general users in rails
- ruby on rails - things associated with a foreign key cannot be called in view
Trends
Only child records specified by specifying a join condition can be joined.
eager_load
can beincludes
, butI think it would have been better to use
eager_load
when it is always combined.