Pregunta

Stage: I am using nested models, supose we have two models: person and car. And here you have new.html.erb page:

<%= form_for(@person do |f| %>
  ...
  <%= f.fields_for :cars do |car| %>
    <div class="field">
      <%= car.label :color %><br />
      <%= car.text_field :color, :maxlength => 7 %>
    </div>
  <% end %>
  ...
<% end %>

This code will generate for each car:

<form ...>
  ...
  <div class="field">
    <label for="person_cars_attributes_0_color">Car color</label><br />
    <input id="person_cars_attributes_0_color" 
           name="person[cars_attributes][0][color]" 
           size="7" type="text" />
  </div>
  ...
</form>

Now suppose we need to put some javascript code for each input field, to generate something like this:

    <script type="text/javascript">
      $(document).ready( function() { $('#person_cars_attributes_0_color').mycolorpicker(); });
    </script>
    <input id="person_cars_attributes_0_color" 
           name="person[cars_attributes][0][color]" 
           size="7" type="text" />

Notice, we need in javascript code input field id (in this example person_cars_attributes_0_color).

Problem: How can we get this id value for each html field generated?

Thank you very much for your help. Please feel free to ask me anything if you need more details.

¿Fue útil?

Solución

How about assigning the field in question an ID or class that you determine before hand?

new.html.erb:

<%= form_for(@person do |f| %>
  ...
  <%= f.fields_for :cars do |car| %>
    <div class="field">
      <%= car.label :color %><br />
      <%= car.text_field :color, :maxlength => 7, :class => 'colorpicker' %>
    </div>
  <% end %>
  ...
<% end %>

JavaScript:

$(document).ready(function() {
  $('.colorpicker').mycolorpicker();
});

Otros consejos

I would highly recommend checking out the nested_form gem by Ryan Bates. I think it will take care of everything that you are looking to do.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top