0
的車型,我有:如何只創建一個遊戲用布爾場真正爲每個提供
類別:
class Category < ApplicationRecord
has_many :categorizations
has_many :providers, through: :categorizations
accepts_nested_attributes_for :categorizations
end
提供者:
class Provider < ApplicationRecord
has_many :categorizations
has_many :categories, through: :categorizations
accepts_nested_attributes_for :categorizations
end
分類:
class Categorization < ApplicationRecord
belongs_to :category
belongs_to :provider
has_many :games, dependent: :destroy
accepts_nested_attributes_for :games
end
遊戲:
class Game < ApplicationRecord
belongs_to :categorization
end
的games
表有most_popular
字段是布爾值。我需要每個提供者只有一個遊戲可以將該布爾字段設置爲true。如果我必須讓只有一個遊戲可以有一個布爾型字段=真,我會做的。像這樣:
class Game < ApplicationRecord
belongs_to :categorization
validate :only_one_most_popular_game
scope :most_popular, -> { where(most_popular: true) }
protected
def only_one_most_popular_game
return unless most_popular?
matches = Game.most_popular
if persisted?
matches = matches.where('id != ?', id)
end
if matches.exists?
errors.add(:most_popular, 'Can\'t have another most popular game.')
end
end
end
那麼,解決這個問題的最好方法是什麼?謝謝你。
隱而不宣不爲我工作。即使對於'categorization_id'沒有'most_popular = true'的遊戲,驗證也不會通過。 –
此外,此代碼涉及分類,但我需要提供商。提供者的ID存儲在分類表中。 –
你的代碼說'Categorization'是'belongs_to:provider'。你是否說你想在所有分類中只有一種「最受歡迎」? – SteveTurczyn