I am using Rails 3, simple_form, and cocoon for a nested form for a Project that has_many TodoLists. I would like my simple_fields_for call to only include TodoLists that have not been soft-deleted, which is why I’d like to use my named scope “nondeleted”.
In my projects 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 fine on first load of my edit view (i.e. deleted TodoLists are not shown), but upon submitting the form with failed validation, any newly added TodoLists are lost.
If I remove the named scope, the newly added TodoLists are not lost upon failed validation, but then all TodoLists (including the deleted ones) are shown.
I’ve 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, such as the ability to keep the TodoLists in their proper order.
Is there a way to pass a collection to simple_fields_for (which, as far as I understand, has the same relevant behaviour as Rails’ fields_for) that will allow me to use a named scope and sorting without dropping newly added fields on failed validation?
I was able to resolve the issue by modifying my Project model’s has_many :todo_lists association as follows:
And in the view it’s simply: