LoginSignup
9
10

More than 5 years have passed since last update.

Rails5 belongs_toを設定において、nilで保存できなくなる?belongs_toのrequiredがデフォルトでtrueに。

Posted at

モデル間に置いてのバリデーションを書いていたら、気づいたことがあるので共有したい思います。

has_many:とbelongs_toの紐付けをする時、
rails5ではデフォルトでrequireになり、通常ではnilでの保存ができなくなる。

class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :confirmable

has_many :pictures

end

class Picture < ApplicationRecord
validates :title, presence: true
belongs_to :user

end

これだけでは、userも一緒に付いてくる。
rails5では新しくoptionalオプションが追加されたので、
belongs_toを設定においてnilの場合は、
optional: trueを追加すれば、
値がnilでも保存できるようになる。

class Picture < ApplicationRecord
validates :title, presence: true
belongs_to :user,optional: true

end

参考にしたサイト
https://www.wantedly.com/companies/wantedly/post_articles/31132
http://zeny.io/blog/2016/07/03/rails-5/

9
10
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
9
10