Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating unique id for <fieldset> when using form_for Rails Nested Model 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 ID. Currently, each field generated has a unique ID and name given by a helper method that assigns a unique ID to every association record. So that is taken cared of. However, this form has "fieldset" tags which isn't assigned an ID. I need a unique ID for each fieldset for jQuery manipulation purposes.

Specifically, how do I do give each fieldset generated for an "Activity" record a unique CSS tag ID? Posted below is how my form is created. 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>
like image 349
Hung Luu Avatar asked Oct 07 '22 03:10

Hung Luu


2 Answers

If you are using ryanb nested_form gem :

Use f.index instead. And make sure that you pass every different form_builder in your partials.

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.

like image 61
Cyril Duchon-Doris Avatar answered Oct 10 '22 10:10

Cyril Duchon-Doris


Why not just use the f.object passed in to both partials?

<% fieldset_id = "#{f.object.class.underscore}_#{f.object.id}" %>
<fieldset id='<%= fieldset_id %>'>
...
like image 33
Ryan Bigg Avatar answered Oct 10 '22 09:10

Ryan Bigg