4
5

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のvalidatesとは?

Posted at

validatesとは?

フォームに値や文字を入力するときに、必須の項目ってありますよね。

スクリーンショット 2019-08-19 21.16.33.png

こんな感じの。会員登録の時、「必ず入力してください」っていう項目、誰でも一度は目にしたことがあると思います。

このように入力欄に制限をかける機能のことをvalidatesといいます。

例:空欄を拒否するvalidation

では、実際にコードを記述してvalidationを設定します。

validationはmodelファイルで設定します。

product.rb
class Product < ApplicationRecord
  validates :name, presence: true
end

validates カラム名, バリデーションの条件の記述でバリデーションを設定しました。

今回はproductモデルのnameカラムにpresence: trueというバリデーションをかけました。

presence: true空ではないという条件のバリデーションです。これによりnameカラムに何らかの文字列が入ってないといけない状態になりました。

例:値を被らないようにするvalidation

次に同じ名前が被らないようnameカラムにバリデーションをかけます。

product.rb
class Product < ApplicationRecord
  validates :user_name, uniqueness: true
end

uniqueness: trueでnameカラムの値がかぶることを防ぐことができます。

様々なバリデーション

バリデーションにはたくさんの種類があるので、以下の記事を参考にしてみてください

Railsバリデーションまとめ

4
5
2

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
4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?