I'm making a Rails app. I've been interested in the N + 1 problem
for a long time, but due to lack of learning about SQL, I often don't notice it myself, so there are places where the N + 1 problem occurs. I decided to put in a gem bullet
that would tell me if there was one.
▶ ︎Official document is here: bullet
Put the following code in the Gemfile.
Gemfile
group :development do
gem 'bullet'
end
After bundle install
, execute the following command.
bundle exec rails g bullet:install
At this time, you will be asked if you want to include bullet
in the test environment, but the official install
says only the installation in the develop
environment.
Looking at Description of installation in official test environment, it seemed to be a lot of trouble (I don't need to spend that much time this time), so I decided not to do it this time.
↑ With the above command, the following code has been added to config/environments/development.rb
by default.
config/environments/development.rb
Rails.application.configure do
#from here
config.after_initialize do
Bullet.enable = true
Bullet.alert = true
Bullet.bullet_logger = true
Bullet.console = true
# Bullet.growl =true Commented out by default
Bullet.rails_logger = true
Bullet.add_footer = true
end
#Up to here is added. Below, the contents originally included in the file are omitted.
end
List of items that can be set in bullet was ← here, but if you check the items that are included by default,
--Bullet.enable
... Enables Bullet gems. But it doesn't do anything.
--Bullet.alert
... Fires a JS alert in your browser.
-- Bullet.bullet_logger
... Get the bullet log file (Location: Rails.root/log/bullet.log)
--Warning to Bullet.console
... console.log.
--Prompts a pop-up warning when Bullet.growl
... Growl
is installed.
--Bullet.rails_logger
... Warns the rails log.
-- Bullet.add_footer
... Displays a message at the bottom left of the screen.
... I see.
When I actually used it, I got a warning like this.
It's convenient because it teaches me how to fix it ^^
By the way, the actual table looks like this. .. .. ..
There was a N + 1
problem with both the users
and images
tables, so fix it like this ...
#before
@posts = Post.order(created_at: 'DESC')
#after
@posts = Post.includes(:user, :images).order(created_at: 'DESC')
In fact, the number of queries has decreased. .. .. ..
Another problem was revealed that the count was spinning a lot: joy:
I was told & researched and found out, but this seems to be another problem, and I was able to solve it with this method!
I want to become familiar with SQL as soon as possible so that I can quickly find, solve, and prevent N + 1 problems: relaxed:
Recommended Posts