bullet icon indicating copy to clipboard operation
bullet copied to clipboard

Bullet eager loading error while saving nested attributes

Open zoras opened this issue 6 years ago • 7 comments

 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?

zoras avatar Apr 23 '18 11:04 zoras

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

MorganFujimaka avatar Jun 10 '18 19:06 MorganFujimaka

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

zoras avatar Jun 11 '18 06:06 zoras

Thanks 👍

MorganFujimaka avatar Jun 11 '18 06:06 MorganFujimaka

Same issue here using accepts_nested_attributes_for

Is there any alternative than skipping this case?

diazweb avatar Feb 12 '20 09:02 diazweb

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.

typhoon2099 avatar Aug 18 '20 10:08 typhoon2099

Same.

ClayShentrup avatar Feb 05 '21 02:02 ClayShentrup

Instead of disabling Bullet warnings in full you can use this instead :

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

subins2000 avatar Aug 04 '22 20:08 subins2000