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

#Rails deny nill value but allow blank value validation / exclusion: { in: [nil] }

Model

class User < ApplicationRecord
  validates :name, exclusion: { in: [nil] }
end

動作イメージ

User.create!(name: nil)

ActiveRecord::RecordInvalid: 名前 は予約されています

User.create!(name: "")
# 成功

ガイド

image

https://railsguides.jp/active_record_validations.html

presence は?

空文字を禁止してしまう

2.9 presence
このヘルパーは、指定された属性が「空でない」ことを確認します。値がnilや空文字でない(つまり空欄でもなければホワイトスペースでもない)ことを確認するために、内部でblank?メソッドを使っています。

class Person < ApplicationRecord
  validates :name, :login, :email, presence: true
end

allow_blank は?

値が未入力、空文字の時にバリデーションをスキップするためオプション指定であり、空文字を許容するわけではない

3.2 :allow_blank
:allow_blankオプションは:allow_nilオプションと似ています。このオプションを指定すると、属性の値がblank?に該当する場合(nilや空文字など)にバリデーションがパスします。

class Topic < ApplicationRecord
  validates :title, length: { is: 5 }, allow_blank: true
end

Topic.create(title: "").valid?  # => true
Topic.create(title: nil).valid? # => true

Original by Github issue

https://github.com/YumaInaura/YumaInaura/issues/2994

YumaInaura
Ruby on Rails 業務経験 約5年 / Perl PHP Python Golang Linux Apache MySQL BigQuery Jenkins ansible AWS など / いなうらゆうま / YumaInaura / 稲浦悠馬
http://twitter.com/yumainaura
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
ユーザーは見つかりませんでした