LoginSignup
1
0

More than 3 years have passed since last update.

アクション内でrenderを使わずにバリデーションエラーや入力していた内容を前ページに反映する方法

Last updated at Posted at 2020-10-06

はじめに

フォーム内容を送信する際、バリデーションに引っ掛かったら
renderメソッドで新規投稿画面をレンダリングして
そこでエラーなり入力していた内容なりを表示すると学習した方が多いはず

しかし、renderメソッドが使えない時はどうしますか?
実は制作中のポートフォリオにGoogleMapAPIを使用しているのですが
renderでページをレンダリングするとなぜかMAPが表示しなくなる不具合が発生...

仕様を変えれば解決できる問題だったのですが、変えたくなかったので
renderを使わずに上記の動きを実現する方法を紹介します。

通常renderを使った場合

例としてtasks_controller.rb
新規投稿ページのアクションnewと、
新規投稿内容を保存するアクションcreateがあるとします。

tasks_controller.rb

def create
  @task = Task.new(task_params)
  if @task.save
    redirect_to @task, notice: 'タスクを保存しました。'
  else
    render :new
  end
end

@task.saveが失敗しelse以下のrender :newが実行され、
新規投稿ページがレンダリングされます。
あとはもうご存知のとおり、viewのほうで@task.errors.full_messagesを活用してく感じですね。

renderを使わない場合

redirect_toで再アクセスをするという形をとり、
エラー文や入力内容はアクション内でflashに格納してしまいます。

tasks_controller.rb

def create
  @task = Task.new(task_params)
  if @task.save
    redirect_to @task, notice: 'タスクを保存しました。'
  else
    flash[:error_msgs] = @task.errors.full_messages
    flash[:tmp_body] = @task.body
    redirect_to new_task_url
  end
end

flash[:error_msgs]にはエラー文を、
flash[:tmp_body]には文章内容を、それぞれ格納しておきます。

あとはアクセス先のviewで、flashの値を活用してすればOKです。
以上!

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