LoginSignup
0
0

More than 3 years have passed since last update.

Ruby on Rails ビューで検証エラーに対応する

Posted at

ビューで検証エラーに対応する

登録画面のフォーム部分が次のようになっている場合

app/views/tasks/_form.html.slim

= form_with model: task, local: true do |f|
  .form-group
    = f.label :name
    = f.text_field :name, class: 'form-control', id: 'task_name'
  .form-group
    = f.label :description
    = f.text_area :description, rows: 5, class: 'form-control', id: 'task_description'
    = f.submit nil, class: 'btn btn-primary'

ここにはまだ検証エラーメッセージを表示する部分がない。
form_withの上に、エラーメッセージを表示するための領域を作りたいので次のように編集。

app/views/tasks/_form.html.slim

- if task.errors.present?
  ul#error_explanation
    - task.errors.full_messages.each do |message|
      li = message

= form_with ...

上記のコードは、errors_present?を使って検証エラーの有無を調べエラーがある時にエラーメッセージを表示するようにしている。

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