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的查詢選項玩耍。 我想要做的是有一個範圍,選擇特定電影的所有評級。使用評分的值屬性計算平均值。如果該值等於或高於所提供的值,則選擇該電影。
如上代碼我一直在玩的加入和平均查詢選項,但我不知道如何將它們在得到我想要的東西結合起來。