Search code examples
ruby-on-railsactiverecordselect-n-plus-1

Rails ActiveRecord N+1 Problem


I have a statement for fetching the following data: food-serving-name, food-name, food-brand-name and food-category. and all the four fields are in different tables. i am using a statement like this

@food_servings = FoodServing.find(params[:food_serving_id], 
                   :include => {:food => [:food_brand,:food_category] })

and the following is my model

FoodServing  belongs_to    Food
                           Food         belongs_to    FoodCategory
                           Food         belongs to    FoodBrand

when i execute the above statement i could see in logs that lot of SQL statements are getting executed, clearly this is N+1 problem, i guess i am passing incorrect include parameter to find method. can anyone help me optimize this call?


Solution

  • I've been using Rails 3 exclusively for awhile now, but I'm pretty sure that's the correct way of solving AR's N+1 query problem in Rails 2.

    Now if you're running that whole line 100x for different FoodServing records, you're still going to see a ton of db hits, as the optimization only applies to each FoodServing.find call, not all of them together.

    I'd say at this point we would need more info from your logs. Which records are being loaded more often than you expect?