0
0

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.

Ruby on Rails モデル検証〜文字列長の検証を追加〜

Posted at

モデルの検証に文字列長の検証を追加

データベースの定義でnameカラムの文字列を30文字以下に制御しているが

app/models/task.rb

class Task < ApplicationRecord
  validates :name, presence: true
end

このままだと、30文字を超える文字列を超える文字列が入力された場合、登録や更新の際に例外が発生してしまう。
これではユーザーが問題の原因に気づきづらく、動線も不便になってしまうので、30文字を超える入力の時に
わかりやすい検証エラーが表示されるようにしたいと思います。

まずTaskモデル(app/models/task.rb)にコードを追加します。

app/models/task.rb
validates :name, length: { maximum: 30 }

これで30文字を超えるとエラーメッセージが返ってきます。

文字数制限を加えたい場合は参考にしてみてください。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?