110
78

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 5 years have passed since last update.

【Rails】modelでboolean型の値をvalidationしたい。【ActiveRecord】

Posted at

Ruby on Railsで開発していて、modelのバリデーションをする時に、

validates :hogehoge, presence: true

ってやると思うんだけど、それboolean型に対してやりたい時はどうするのって話。

例えば admin:boolean ってのがあるとして、

validates :admin, presence: true # コレだと admin == falseの時にエラーが出る。

コレだと admin == false の時にエラーを吐いてしまう。

じゃあどうすればいいのかというと、 inclusion を使うらしい。

validates :admin, inclusion: {in: [true, false]}

これでOK!

110
78
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
110
78

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?