2017-03-16 19 views
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 

那麼,解決這個問題的最好方法是什麼?謝謝你。

回答

1

你不想看所有的games,你只想看看那個分類。

def only_one_most_popular_game 
    return unless most_popular? 
    if categorization.games.most_popular.where('id != ?', id).first 
    errors.add(:most_popular, 'Can\'t have another most popular game.') 
    end 
end 

編輯

您還可以指定

class Provider < ApplicationRecord 
    has_many :games, through: :categories 

(以上要求的Rails 3.1或更高版本)

,這將讓你做......

if categorization.provider.games.most_popular.where('games.id != ?', id).first 
+0

隱而不宣不爲我工作。即使對於'categorization_id'沒有'most_popular = true'的遊戲,驗證也不會通過。 –

+0

此外,此代碼涉及分類,但我需要提供商。提供者的ID存儲在分類表中。 –

+0

你的代碼說'Categorization'是'belongs_to:provider'。你是否說你想在所有分類中只有一種「最受歡迎」? – SteveTurczyn