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
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.
I tried to try
Rails ## controller @groups = Group.includes (: users) .where (gender: male) .references (: users) ## view @ groups.each do | group | group.name end
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")
I think it would have been better to use
eager_loadwhen it is always combined.
- 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