Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Nested N+1 Query Issue

My Associations are like this:

vendor has shipments  
shipment has order
order has products

In My controller I have written as

@shipments = @vendor.shipments.includes(:order)

But in my view I am using like

shipment.order.products.collect(&:name)

So it is returning N+1 Query issue by Rails 'bullet' gem

Anyone Help me to resolve this problem of Nested N+1 Query Issue? How I need to write in the controller?

like image 969
Abhi Avatar asked Nov 27 '12 12:11

Abhi


People also ask

What is N 1 query problem rails?

The n+1 query problem is one of the most common scalability bottlenecks. It involves fetching a list of resources from a database that includes other associated resources within them. This means that we might have to query for the associated resources separately.

How do you stop n 1 queries?

You can avoid most n+1 queries in rails by simply eager loading associations. Eager loading allows you to load all of your associations (parent and children) once instead of n+1 times (which often happens with lazy loading, rails' default).

What are some strategies to solve the N 1 Select problem in hibernate?

Hibernate N+1 issue occurs when you use `FetchType. LAZY` for your entity associations. Hibernate will perform n-additional queries to load lazily fetched objects. To escape this issue use join fetch, batching or sub select.

What is laravel n1 problem?

What is the N+1 Query Problem. In short, it's when Laravel code runs too many database queries. It happens because Eloquent allows developers to write a readable syntax with models, without digging deeper into what "magic" is happening under the hood.


1 Answers

@shipments = @vendor.shipments.includes(:order => :products)

should work. Read more about it here http://guides.rubyonrails.org/active_record_querying.html#nested-associations-hash

like image 108
Vasiliy Ermolovich Avatar answered Oct 03 '22 22:10

Vasiliy Ermolovich