Frage

I have a Category model that has_many :items. The items have a deleted boolean field that checks if the item has been deleted or not. When listing all the categories, I also want to print the count of deleted: false items in that category

This is how I'm doing it

@categories = Category.includes(:items).all

When printing out the counts of not deleted items, I'm doing

category.items.get_all.count

get_all is a scope inside item model

scope :get_all, where(deleted: false)

It's getting the job done, however I feel the page load time to be slower than other pages on my website. Is there any way I can optimize this code?

War es hilfreich?

Lösung

You are getting N+1 queries due to the scope get_all which executes a query for items of each category.

The actual solution to the problem of slow load time depends on which query is making it slow. See the server query logs to figure that out and post them if you need help.

The N+1 query problem can be solved by getting the count in Ruby itself like this:

 category.items.select{|i| !i.deleted}.count
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top