Ruby on rails 如何为每个提供者仅创建一个布尔字段为true的游戏

Ruby on rails 如何为每个提供者仅创建一个布尔字段为true的游戏,ruby-on-rails,validation,Ruby On Rails,Validation,我拥有的模型: 类别: class Category < ApplicationRecord has_many :categorizations has_many :providers, through: :categorizations accepts_nested_attributes_for :categorizations end class Provider < ApplicationRecord has_many :categorizations h

我拥有的模型:

类别:

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

那么,解决这个问题的最佳方式是什么?谢谢你。

你不想看所有的
游戏,你只想看那些分类的游戏

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

不适合我。即使对于没有
most\u populary=true
categorization\u id
游戏,验证也不会通过。此外,此代码涉及分类,但我需要提供程序。提供者的id存储在分类表中。您的代码显示
分类
属于:提供者
。你是说在所有分类中你只想要一个“最受欢迎的”吗?我只需要每个提供者有一个“最受欢迎的”。也许我应该重构模型关系?我的编辑应该处理验证。Rails 3.1允许嵌套的
有许多
,因此可以为提供商访问所有游戏
class Provider < ApplicationRecord
  has_many :games, through: :categories
if categorization.provider.games.most_popular.where('games.id != ?', id).first