Reputation: 682
Why doesn't the Ruby on Rails framework provide a method to understand if an operation I'm doing will cause a query or not?
Take a User that has many Posts
in my view I will do:
<% @user.posts.each do |p| %>
<%= p.title %>
<% end %>
I have no way to see if in my controller I did
@user = User.find(params[:id]).includes(:posts)
that is an eager loading, and causes one query, with a left join, or if I did:
@user = User.find(params[:id])
that causes n+1 queries
If the application is simple, there wouldn't be any problem, but let's take a larger application. Maybe the query method is not in the controller, but in the model. And maybe it's not even in the model, but in a concern (an external module, included my the model).
in other words I have the impression of losing control of what the framework is doing with my database.
Did you find any solutions for this problem?
Upvotes: 1
Views: 64
Reputation: 1174
You can add bullet gem in your application which will prompt for n+1 queries
Add this gem in your application
gem "bullet", :group => "development"
Add below settings in your configuration file config/environments/development.rb
config.after_initialize do
Bullet.enable = true
Bullet.alert = true
Bullet.bullet_logger = true
end
After that you should be able to monitor n+1 queries
More reference can be checked in below link
https://github.com/flyerhzm/bullet
Upvotes: 1