rails 技術ブログ

rails 技術ブログ

勉強したことをアウトプットしていきます

uniqueness: { scope: }を使ってユニーク制約を実装する

ブックマーク機能を実装したいと考えた時、「掲示板のユーザーは1つの掲示板に対して1ブックーマークしかできない」はずなので、そのためのバリデーションを設定します。

それを設定するのが以下のvalidates :user_id, uniqueness: { scope: :board_id }という記述です。

class Bookmark < ApplicationRecord
  belongs_to :user
  belongs_to :board
  validates :user_id, uniqueness: { scope: :board_id }
end