【发布时间】:2015-10-24 14:18:09
【问题描述】:
这个特定主题有很多答案,但我找不到任何一个非常适合我。我有一个食谱应用程序,其中我需要所有对该食谱给予特定评级的用户(例如:对特定食谱给予评级 5 的用户列表)而没有 n+1 查询错误。我知道它可以使用包含选项来解决,但在属于参考中我不知道如何使用它。我正在使用 Rails 3.2.15。
以下是我的应用程序的模态级别描述
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
我检索用户的查询是
@rec = Recipe.find(params[:id])
ratings = @rec.ratings.where(:ratings => params[:ratings])
users = ratings.map {|rate| rate.user}
这引入了一个 n+1 查询错误,请问有什么正确的方法可以使用 rails 吗?
【问题讨论】:
标签: ruby ruby-on-rails-3 postgresql activerecord