2015-03-31 112 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來測試它是否可行。