ruby on rails - How to improve the query so as to reduce the time taken? -
consider have 15 categories , each category has 6 sub-categories , have items table have find 3 items each sub-category based on latest purchased date.
category 1 ---> level 1 ---> 3 items latest date category 1 ---> level 2 ---> 3 items latest date ... ... ... category 15 ---> level 5 ---> 3 items latest date category 15 ---> level 6 ---> 3 items latest date i have tried
@categories.each |value| @sub-categories.each |value1| array = item.find(:all, :conditions => ["customer_id in (?) , category_id = ? , sub-category_id = ?", @customer, value.id, value1.id], :order => 'created_at desc', :limit => 3) array.each |value2| @latest_item_of_each_customer << value2 end end end this repeat fro 90 times 15categories x 6sub-categories, take time. please tell me how can reduce time efficient query.
depending on size of data set pulling in, 1 way speed nested loop eager load of associations.
@categories = category.all(:include => :sub_categories) this should reduce amount of queries making , therefor improve performance.
if want read more on eager loading take @ http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations
Comments
Post a Comment