平均值范围

时间:2015-03-31 09:42:37

标签: sql ruby-on-rails activerecord

我正在尝试在我的电影模型上定义一个范围,以便选择平均评分高于提供值的所有电影。

到目前为止,我有以下模型:

class Movie < ActiveRecord::Base
  # Callbacks & Plugins

  # Associations
  has_and_belongs_to_many :categories
  has_many :ratings

  # Validations
  validates :name, presence: true, uniqueness: true
  validates :description, presence: true

  # Scopes
  scope :category, -> (category) { joins(:categories).where("categories.id = ?", category) }
  scope :searchable, -> (query) { where("name LIKE '%?%'", query) }
  scope :rating, -> (rating) { joins(:ratings).average("ratings.value")) }
end

class Rating < ActiveRecord::Base
  # Callback & plugins

  # Associations
  belongs_to :user
  belongs_to :movie, counter_cache: true

  # Validations
  validates :value, presence: true, numericality: { only_integer: true, greater_than_or_equal_to: 1, less_than_or_equal_to: 5 }
  validates :user, presence: true, uniqueness: { scope: :movie_id }
end

现在我正在玩Rails中的查询选项。 我想要做的是有一个范围,选择特定电影的所有评级。使用评级的属性计算平均值。如果该值等于或高于提供的值,则选择该电影。

正如代码中我一直在使用加入平均查询选项,但我不确定如何将它们组合起来以获得我想要的内容。

1 个答案:

答案 0 :(得分:0)

想想我发现了......

scope :rating, -> (rating) { joins(:ratings).group("movies.id").having("AVG(ratings.value) > ? OR AVG(ratings.value) = ?", rating, rating) }

为我生成以下查询:

 Movie Load (1.9ms)  SELECT "movies".* FROM "movies" INNER JOIN "ratings" ON "ratings"."movie_id" = "movies"."id" GROUP BY movies.id HAVING AVG(ratings.value) > 1 OR AVG(ratings.value) = 1

这就是我想要的。现在用一些Rspec测试它是否有效。

相关问题