LoginSignup
104
89

More than 5 years have passed since last update.

Formに入力した値を維持したままリロードする方法

Posted at

フォームに値を入力したがValidatesに引っかかり、もう一度入力し直し。。。その時にページがリロードされ、さっき入力した値がまっさらに消えて、直さなくて良いところも入力し直し。。。それはあまりにも酷だ!!!

ということで、入力失敗した時に値を保持したままリロードする方法について記します。

だいたいformを使用して値を保存するアクションはcreateかupdateだと思うので、create、updateを例に紹介します。

createアクションの場合

まずnewアクション内で@hoge = hoge.newという空のインスタンス変数を作り、
そして、createアクションで@hoge = hoge.new(params[:hoge])と書く。この際に、フォームで入力した値はparams[:hoge]に値を格納されています。

なので、エラーしrenderで再びnewアクションに戻したいといった際、rende `new`の前にparamsの値を代入してあげれば良いのです。

実際に書いてみるとこんな感じでしょうか。

hoges_controller.rb
def new
    @hoge = Hoge.new
end

def create
  @hoge = Hoge.new(user_params)
  if @hoge.save
    redirect_to 'static_pages/top'
    flash[:success] = "Welcome to the Hoge App!"
  else
    @hoge = Hoge.new(user_params) #newで入力した値を代入
    render 'new'
  end
end

updateアクションの場合

updateする際、update_attributes(params[:hoge])というメソッドを使用するかと思います。
この`update_attributes

@hoge.attributes = params[:hoge]

@hoge.save
を一気に行ってくれる便利なメソッドです。

今回でいうと、@hoge = hoge.attribute(params[:hoge])の中に入力された値が格納されているので、これをrennderの前に代入しましょう。

hoges_controllers.rb
def update
  @hoge = Hoge.find(params[:id])
  @hoge.update_attributes(params[:hoge])
  if @hoget.save
    flash[:notice] = "更新しました!"
    redirect_to 'index'
  else
    @hoge.attributes = params[:hoeg]
    flash[:notice] = "失敗しました!"
    redirect_to edit_hoge_path
  end
end
104
89
1

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
104
89