Create a unique identifier for <fieldset> when using form nested form form_for Rails form

I have a nested model form in the style of this Railscast http://railscasts.com/episodes/196-nested-model-form-revised?view=asciicast

I need to give each tag a unique identifier. Currently, each generated field has a unique identifier and a name specified by a helper method that assigns a unique identifier to each association record. So take care of it. However, there are "fieldset" tags in this form that are not assigned an identifier. I need a unique identifier for each set of fields for jQuery manipulation purposes.

In particular, how do I give each set of fields generated for an "Activity" entry a unique CSS tag identifier? Below is a way to create my form. thank you

_form.html.erb

<%= form_for(@trip) do |f| %> <%= f.fields_for :days do |builder| %> <%= render 'day_fields', f: builder %> <% end %> <%= link_to_add_fields "Add Day", f, :days %> 

_day_fields.html.erb partial

 <fieldset> <%= f.label :summary, "Day Summary" %><br /> <%= f.text_area :summary, :rows => 1 %><br /> <%= link_to "remove", '#', class: "remove_fields" %> <%= f.fields_for :activities do |builder| %> <%= render 'activity_fields', f: builder %> <% end %> <%= link_to_add_fields "Add Activity", f, :activities %> </fieldset> 

_activity_fields.html.erb

 <fieldset> <%= f.label :title, "Activity" %><br /> <%= f.text_field :title, :rows => 1 %><br /> <%= f.hidden_field :_destroy %> <%= link_to "remove", '#', class: "remove_fields" %> </fieldset> 
+4
source share
3 answers

If you are using ryanb nested_form gem:

Use f.index instead. And make sure you go through each individual form_builder in its parts.

For example, if you do

 <%= main_form.fields_for :nested1_items do |nested1_form| %> <%= render partial 'main/nested1_fields', nested1_form: nested1_form %> <% end %> 

_nested1_fields

 <fieldset id="nested1-<%= nested1_form.index %>-items"> 

See my answer in this question .

+2
source

Why not just use the f.object tag for partial ones?

 <% fieldset_id = "#{f.object.class.underscore}_#{f.object.id}" %> <fieldset id='<%= fieldset_id %>'> ... 
+1
source

I had a similar problem, and I solve it using the time in seconds, and pass it on to everyone where I need it.

For instance:

in the controller

 def something # First idea @dynid = Time.now.to_i ... # Second idea: store it in the session session[:dynid] = Time.now.to_i ... end 

in view

 <fieldset id="#{@dynid}"> <!-- or in case @dynid is out of reach, then use the session[:dynid] --> <fieldset id="#{session[:dynid]}"> 

session[:dynid} will work even with ajax-processed code.

Hope this helps you.

0
source

Source: https://habr.com/ru/post/1443583/


All Articles