Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

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

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/

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした