web-dev-qa-db-ja.com

Railsカスタム検証-1つのレコードのみがtrueになります

1つのレコードのみが真になる検証を作成しようとしています。 「アクティブな」ブール列を持つ「ゲーム」モデルがあります。一度にアクティブにできるゲームは1つだけなので、すでにアクティブなゲームがあるときに誰かが新しい「ゲーム」レコードを作成しようとすると、エラーが発生するはずです。 。以下は私が現在持っているものですが、機能していません!

validate :active_game

  def active_game
    if active == true && Game.find_by(active: true) == true
       errors[:name] = "a game is already active!"
    end
  end
21
raphael_turtle

レコードがすでに永続化されている場合は、IDと照合する必要もあります。そうしないと、既存のアクティブなゲームが存在するため、アクティブなゲームを再度保存することはできません。

validate :only_one_active_game
scope :active, where(:active => true)

protected

def only_one_active_game
  return unless active?

  matches = Game.active
  if persisted?
    matches = matches.where('id != ?', id)
  end
  if matches.exists?
    errors.add(:active, 'cannot have another active game')
  end
end
10
kristinalim

Active_gameがtrueの場合、その一意性を確認できると思います。

validates_uniqueness_of :active_game, if: :active_game

60
onurozgurozkan

exists?メソッドを使用してみてください。また、addメソッドを使用してエラーを追加します。

validate :active_game
scope :active, where(active: true)

  def active_game
    if active && Game.active.where("id != ?", id).exists?
       errors.add(:name, "a game is already active!")
    end
  end
0
lightswitch05