-
Notifications
You must be signed in to change notification settings - Fork 385
Manually setting the index of a new element
Carles Jove i Buxeda edited this page Nov 29, 2018
·
1 revision
If you have a field whose name
attribute has to be manually written, you may want its index to be properly set by both Cocoon and Rails' form builder. Since Rails 4, you can do so by getting the index
from the form builder.
<%= f.label :month %>
<%= select_month f.object[:month], {}, { name: "parent[childs_attributes][#{f.index}][month]" } %>
In this example we're using select_month
, which only works as a standalone method, but can't be used with the form builder. Notice that we add f.index
, which will add:
-
new_childs
when is a new record (added by Cocoon) - the numeric index when it's a persisted record
This works because Cocoon itself replaces all instances of new_child
when adding a new element, following Rails' naming conventions.