0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

railsのbelongs_toに指定できるoptional: true

Posted at

class Task < ApplicationRecord
  has_many :user
end


class User < ApplicationRecord
  belongs_to :task, optional: true
end

このoptional: trueとは何なのか?

これはbelongs_toの外部キーのnilを許可するというもの!

上記のコードであれば、User.task_idが外部キーとなり、値がセットされていない場合はバリデーションで弾かれるが、optional: trueを設定しておくと、外部キーがnilであってもDBに保存できる!

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?