Home > other >  How to solve "N 1" with Ruby on Rails
How to solve "N 1" with Ruby on Rails

Time:10-12

Creating a web application with Ruby on Rails.
In the midst of all this, the N 1 problem arose, I have tried eager_load, but it does not solve the problem.
I would be grateful if you could tell me about the solution.

# companies_controller.rb

companies = Company.with_include_users
users = User.with_include_company

companies.each do |company|
  ActiveRecord::Base.transaction do
    target_user = users.where(id: company.id)
    pp target_user
  end
end
# company.rb

has_many :users
scope :with_include_users, -> {
  eager_load(:users)
}
# user.rb

belongs_to :company
scope :with_include_company, -> {
  joins(:company).eager_load(:company)
}

As shown above, we eager_load in the model and outer join. In fact, it has not been resolved.

CodePudding user response:

In order to resolve the n 1 problem, you can use the method includes to get your associated objects directly, if you know that you will have to use them in your view.

(untested code bellow)

# companies_controller.rb

companies = Company.includes(:users)

companies.each do |company|
  company.users.each do |user|
    pp user
  end
end
  • Related