はじめに
ある属性に対して一意なバリデーションをかけたいときがあります。そのような際に便利なuniqueness: scope
を利用してバリデーションをかける方法について解説します。
通常の使い方
class PostTag < ApplicationRecord
belongs_to :tag
belongs_to :post
validates :tag_id, uniqueness: true
end
この書き方はtag_id
がテーブル全体で一意な値という意味になってしまいます。
scopeを使うやり方
class PostTag < ApplicationRecord
belongs_to :tag
belongs_to :post
validates :tag_id, uniqueness: { scope: :post_id }
end
同じ投稿に対するタグの組み合わせは1つのみなので、tag_id
とpost_id
の組み合わせは一意でなければいけません。そのためには、一意性チェックの範囲を限定する別の属性を指定する:scope
オプションを設定する必要があります。uniqueness: { scope: :post_id }
とすることで、タグは投稿に対しての組み合わせは一つだけですよ。という意味合いを持たせることができます。
コメント