Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
10
Help us understand the problem. What is going on with this article?
@ARTS_papa

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/

10
Help us understand the problem. What is going on with this article?
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.
Sign Up
If you already have a Qiita account Login
10
Help us understand the problem. What is going on with this article?