0
votes

For various reasons I need to avoid traditional nested forms (nested in the sense of treating the fields like a sub-group of the primary model for the page), but still want to keep fields grouped together with an index-style naming, so I have this:

<%= simple_fields_for :crate_request do |ff| %>
 <%= ff.input :_create, :label => "crate needed", :as => :boolean %>
 <%= ff.input :details, :as => :text %>
<% end %>

The rendered fields are named as expected (with names like params[:crate_request][:details]) and all looks well until I submit a form with validation errors and it has to come back to re-render. The fields don't prefill with the submitted values stored in the params hash. Although I'm using simple_form, it doesn't seem to just be a simple_form issue. The native Rails helpers appear to do the same.

So the question: is there any way to have the fields automatically pre filled from the params hash again without having to manually set the value of each field from params?

2

2 Answers

1
votes

You would just need to pass some object as an extra argument to simple_fields_for.

As the form builder expects the object to have field accessors as methods, but you've only got a hash (params[:create_request]), you can use OpenStruct to create an object which would translate missing method calls to hash lookup.

The final solution then would look something like this:

<%= simple_fields_for :create_request, OpenStruct.new(params[:create_request]) do |ff| %>
  ...
<% end %>
-1
votes

Replace

<%= ff.input :details, :as => :text %>

by

<%= input :details, :as => :text %>