Consider i have 15 categories and each category has 6 sub-categories and now i have items table where i have to find 3 items from each sub-category based on the latest purchased date.
category 1 ---> level 1 ---> 3 items with latest date
category 1 ---> level 2 ---> 3 items with latest date
...
...
...
category 15 ---> level 5 ---> 3 items with latest date
category 15 ---> level 6 ---> 3 items with latest date
I have tried
@categories.each do |value|
@sub-categories.each do |value1|
array = Item.find(:all, :conditions => ["customer_id IN (?) AND category_id = ? AND sub-category_id = ?", @customer, value.id, value1.id], :order => 'created_at DESC', :limit => 3)
array.each do |value2|
@latest_item_of_each_customer << value2
end
end
end
This would repeat fro 90 times as 15categories x 6sub-categories, so it would take much time. please tell me how i can reduce the time by efficient query.
Depending on the size of the data set you are pulling in, one way to speed up a nested loop like this would be to eager load some of those associations.
@categories = Category.all(:include => :sub_categories)
This should reduce the amount of queries you are making and therefor improve performance.
If you want to read up some more on eager loading take a look at this http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations
1) First thing is... what is the use of category_id in item table, as we already have sub_category_id, and from sub_category we can get category and you want items for each subcategory.
@latest_item_of_each_customer = []
@sub_categories = SubCategory.all
@sub_categories.each do |value1|
@latest_item_of_each_customer << Item.find(:all, :conditions => ["customer_id IN (?) and sub_category_id = ?", @customer, value1.id], :order => 'created_at DESC', :limit => 3)
end
@latest_item_of_each_customer = @latest_item_of_each_customer.flatten
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.