1

Rails 5.

New app, all default.

Bullet gem tell me this:

user: root
/children/2
N+1 Query detected
  Child => [:parent]
  Add to your finder: :includes => [:parent]
N+1 Query method call stack
  app/controllers/children_controller.rb:14:in `show'
app/controllers/children_controller.rb:14:in `show'

I have these models:

class Parent < ApplicationRecord

    has_many :children

end

class Child < ApplicationRecord

    belongs_to :parent

end

I have this controller in children_controller.rb with:

...

def show
    @parent = @child.parent
end
...

In my views views/children/show.html.erb I have this:

...
<%= @parent.name %>
...

If I invert this and in view I put:

<%= @child.parent.name %>

and in controller:

...

def show
    #nothing more
end
...

I have the same error from Bullet but in html.

How to fix this? Is really a N+1 problem or Bullet is wrong?

The project is really really new. First models.

  • Hi: please check that the value of @child in your show action (in the controller) is not nil. You'll have to fetch the record somehow: e.g. '@child = Child.first to see if it's working? – BenKoshy Aug 27 '16 at 02:20
  • You might get a kick out of http://stackoverflow.com/questions/26247288/reducing-n1-queries-using-the-bullet-and-rspec-gems and – Brad Werth Aug 27 '16 at 03:58
  • @BKSpurgeon, it's not nil. –  Aug 27 '16 at 08:09

1 Answers1

2

I don't think its a N+1 problem as a child has only one parent. However, you can use includes, if that makes a difference:

@child = Child.includes(:parent).find(1)

But if you try both on terminal, you will see that ActiveRecord generates 2 SQL statements with and without the includes.

Paulo Abreu
  • 1,716
  • 11
  • 16