LoginSignup
0
0

More than 5 years have passed since last update.

一意性制約のscopeオプション

Posted at

一意性制約とは

別のレコードに保存されている値を保存できなくする制約です。

User.rb
class User < ApplicationRecord 
  validates :email, uniqueness: true 
end 

本題

現在学習の記録が出来るサービスを作成しています。
投稿に必要な項目の中に学習日があります。(learning_dateというカラム名にします)
同じ日の学習記録は出来ないようにしたいので一意性制約をかけます。

Post.rb
class Post < ApplicationRecord
  belongs_to :user
  validates  :learning_date, presence: true, uniqueness: true
end

これで良さそうに見えますがこのバリデーションのかけ方だと問題が生じます。 
このバリデーションのかけ方をすると
他のユーザーが投稿した学習日の学習記録も投稿出来なくなってしまいます。

では、どうするか、、、

ここでscopeオプションを使います!

Post.rb
class Post < ApplicationRecord
  belongs_to :user
  validates  :learning_date, presence: true, uniqueness: { scope: [:user_id] }
end

上記の書き方だとuser_idとlearning_dateが同じ場合にバリデーションがかかります。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0