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?
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.
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).
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 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.
@shipments = @vendor.shipments.includes(:order => :products)
should work. Read more about it here http://guides.rubyonrails.org/active_record_querying.html#nested-associations-hash
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With