dimanche 2 août 2015

Avoiding n+1 query bug in rails has many association

There are many answers with this particular topic but I am not finding any one perfectly suited for me. I have a recipe app where in I need all the users who gave particular ratings to that recipe(example: list of user who gave rating 5 to particular recipe) without having an n+1 query bug. I know it can be solved using includes option but in belongs to reference I don't know how to use it. I am using rails 3.2.15.

below is the modal level description of my app

class Recipe < ActiveRecord::Base
  belongs_to :user, :foreign_key => 'creator_id'
  has_many :photos, :dependent => :destroy
  has_many :recipe_ingredients
  has_many :ingredients, :through => :recipe_ingredients
  has_many :ratings, :dependent => :destroy
end


class  Rating < ActiveRecord::Base
  belongs_to :user, :foreign_key => 'rater_id'
  belongs_to :recipe
end

class Ingredient < ActiveRecord::Base
  belongs_to :user, :foreign_key => 'creator_id'
  has_many :recipe_ingredients
  has_many :recipes, :through => :recipe_ingredients 
end

class User < ActiveRecord::Base
  has_many :recipes , foreign_key: "creator_id", class_name: "Recipe", :dependent => :destroy
  has_many :ingredients, foreign_key: "creator_id", class_name: "Ingredient", :dependent => :destroy
  has_many :ratings, foreign_key: "rater_id", class_name: "Rating", :dependent => :destroy
end

My query to retieve users is

@rec = Recipe.find(params[:id])
ratings = @rec.ratings.where(:ratings => params[:ratings])

users = ratings.map {|rate| rate.user}

this introduces an n+1 query bug is there any proper way in use rails?

Aucun commentaire:

Enregistrer un commentaire