flyerhzm / bullet

help to kill N+1 queries and unused eager loading
MIT License
7.07k stars 432 forks source link

Bullet eager loading error while saving nested attributes #402

Open zoras opened 6 years ago

zoras commented 6 years ago
 RUBY_VERSION
=> "2.5.1"
Rails.version
=> "5.2.0"
# User.rb
has_one :profile, dependent: :destroy
accepts_nested_attributes_for :profile

# Event.rb
belongs_to :user
has_one :profile, through: :user
accepts_nested_attributes_for :user

Given above conditions saving event with nested user and profile params raises bullet error

event_params = { 
  type: 'Party', 
  user_attributes: { 
    first_name: 'some', 
    profile_attributes: { shirt_size: 'M' } 
  }
}

Event.includes(user: :profile).save(event_params)

Bullet::Notification::UnoptimizedQueryError:
       user: zoras
       POST /events
       USE eager loading detected
         User => [:profile]
         Add to your finder: :includes => [:profile]

I doubt this is a false positive or something can be done?

MorganFujimaka commented 6 years ago

Hey Zoras, did you manage to solve the issue? I have a pretty similar one.

zoras commented 6 years ago

Nop, I've skipped the bullet warnings by whitelisting https://github.com/flyerhzm/bullet#whitelist

# application_controller.rb
def skip_bullet
  Bullet.enable = false if %w(development test).include?(Rails.env)
  yield
ensure
  Bullet.enable = true if %w(development test).include?(Rails.env)
end

# some_controller.rb
around_action :skip_bullet, only: :action
MorganFujimaka commented 6 years ago

Thanks 👍

diazweb commented 4 years ago

Same issue here using accepts_nested_attributes_for

Is there any alternative than skipping this case?

typhoon2099 commented 4 years ago

I'm experiencing the same issue, I have nested attributes which raises an N+1 error, though in my case the relationship is one to many and the warning comes from a many to one association on the nested model being updated.

ClayShentrup commented 3 years ago

Same.

subins2000 commented 2 years ago

Instead of disabling Bullet warnings in full you can use this instead to just disable USE eager loading detected :

Bullet.n_plus_one_query_enable = false
// do stuff in test
Bullet.n_plus_one_query_enable = true

Number of times I've come here into this issue and surprised myself seeing my reply from years ago: 3