Keep form fields filled after an error (RoR)

前端 未结 2 837
难免孤独
难免孤独 2020-12-06 09:18

After validation, I got an error and I got returned back to :action => :new. Some field on form already filled, so I want to keep them filled even after erro

相关标签:
2条回答
  • 2020-12-06 09:43

    Your View (new.html.erb) something like following

    <%= error_message_for :user %>
    <% form_for :user, :action=>"create" do|f|%>
    
    <%= f.text_field :login %>
    
    <% end %>
    

    Controller Code (create method)

    def create
      @user=User.new(params[:user])
      if @user.save
         redirect_to :action=>'index'
      else
         render :action=>'new'  #you should render to fill fields after error message
      end
    end
    
    0 讨论(0)
  • 2020-12-06 09:48

    Since in my case the form was in the view of another controller I did use flash to store my data and then check if there is data in flash present. If yes take this for default values for your input fields, if not just show whatever you want to show then.

    So snippets from my code

    flash[:date] = start_date
    
    # in the view where to form resides
    start_day = flash[:date].nil? nil : flash[:date].day
    # ...
    <%= select day start_day ... %>
    

    Hope that helps some of you ;-).

    0 讨论(0)
提交回复
热议问题