2015-03-31 190 views
0

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

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

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的查询选项玩耍。 我想要做的是有一个范围,选择特定电影的所有评级。使用评分的属性计算平均值。如果该值等于或高于所提供的值,则选择该电影。

如上代码我一直在玩的加入平均查询选项,但我不知道如何将它们在得到我想要的东西结合起来。

回答

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来测试它是否可行。