Rails: Restoring contents of non-model form that u

2019-02-23 02:46发布

I'm making good progress with my first Rails app (using Rails 3). The MVC interaction is all going fine, but I'm having difficulty with a form that doesn't relate directly to a model.

I'm using form_tag, and in the case of success, everything behaves fine. However, the handling of errors is somewhat unfriendly. The actual error message is stored in the flash and displayed fine by layouts/application.html, but I'd really like it if the form could remember the contents that the user had just filled in. But it doesn't: all the fields reset to their default values.

I love the way that forms for RESTful actions on objects automatically remember their submitted values, and get highlighted in red if there are errors. I'm fine without the red highlight, but I'd really like it if I could make the form's fields keep the submitted values.

Can anyone advise how to do this?

Excerpts from the relevant files:

views/cardsets/import.html.erb:

<%= form_tag :action => :import_data, :id => @cardset do %>
  ...
  <%= text_field_tag "separator", "", :maxlength => 1 %>
  ...
  <%= text_field_tag "formatting_line" %>
  ...etc (more fields)

controllers/cardsets_controller.rb:

# POST /cardsets/1/import_data
def import_data
  success, message = @cardset.import_data(params, current_user)
  if success
    redirect_to(@cardset, :notice => message)
  else
    flash.now[:error] = message
    render :import
  end
end

2条回答
叼着烟拽天下
2楼-- · 2019-02-23 03:44

If your field has a default, you will want to set it from the "show" action for the form:

# GET
def show_form
  params[:key] = 'default'
end

# POST
def validate_form_and_act
  # Don't set it here to reuse what the user passed.
end

or directly on the template (less good because uses an || every time and adds more controller data to view):

 <%= text_field_tag 'name', params[:key] || 'default' %>
查看更多
闹够了就滚
3楼-- · 2019-02-23 03:49

The second arg to text_field_tag is the value to fill in the field with. Try something like this:

  <%= text_field_tag "separator", params[:separator], :maxlength => 1 %>
查看更多
登录 后发表回答