Rails 3 fields_for with field reset field when validation fails

I use Rails 3, simple_form and a cocoon for a nested form for a project with has_many TodoLists. I would like my simple_fields_for call to include only TodoLists that were not gently removed, so I would like to use my named scope "nondeleted".

In my project form, I have:

<%= f.simple_fields_for :todo_lists, f.object.todo_lists.nondeleted do |todo_list_form| render "todo_list_fields", :f => todo_list_form end %> 

This works great the first time I load my edit (i.e. deleted TodoLists are not displayed), but after submitting a form with a failed check, all new TodoLists added are lost.

If I delete the named scope, the newly added TodoLists will not be lost after a failed check, but then all TodoLists (including deleted ones) will be shown.

I also tried the following:

 <% @project.todo_lists.each do |todo_list| %> <% if !todo_list.deleted && !todo_list.name.blank? %> <%= f.simple_fields_for :todo_lists, todo_list do |todo_list_form| render "todo_list_fields", :f => todo_list_form end %> <% end %> <% end %> 

This solves both problems, but does not allow me the flexibility I need, for example, the ability to keep TodoLists in the correct order.

Is there a way to pass the collection to simple_fields_for (which, as I understand it, has the same relevant behavior as the Rails_for fields) that will allow me to use the named area and sort, without discarding the newly added fields if the validation fails?

+4
source share
2 answers

I was able to solve the problem by changing my has_many: todo_lists project model, as shown below:

 has_many :todo_lists, :conditions => { :deleted => false }, :order => :name 

And in the view, it's simple:

 <%= f.simple_fields_for :todo_lists do |todo_list_form| render "todo_list_fields", :f => todo_list_form end %> 
0
source

the default area may also solve the problem

 class Foo < ActiveRecord::Base has_many :bars end class Bar < ActiveRecord::Base default_scope { where(active: true) } end 

and

 <%= f.simple_fields_for :bars ... %> 
0
source

All Articles