3

I am trying to get the following result:

<input class="file required" id="page_media_attributes_1367414416272_image" multiple="multiple" name="page[media_attributes][1367414416272][image]" type="file">

Is there any dynamic tag I can add to this:

<div class='span3'> 
  <%= f.input :image, as: :file, :input_html => { :multiple => true, :name => 'page[media_attributes][Something dynamic][image]' } %>
  <%= f.input :name %>

  <%= link_to_remove_association "remove image", f %>
</div>

That would insert the number 1367414416272 instead of [Something dynamic] to get the html above?

The number is different every time, and I believe it is generated by Cocoon since these fields are added dynamically by cocoon.

Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
Ole Henrik Skogstrøm
  • 6,353
  • 10
  • 57
  • 89

1 Answers1

3

Yes, the numbers are automatically generated by Cocoon. From the "add new" javascript function of cocoon:

new_id = new Date().getTime() + cocoon_element_counter++

I think you have to use javascript too in order to find all "cocoon" elements and parse their id attribute to get the random number and then change their name accordingly.

Draft:

$(document).ready(function(){
    $('input[id^="page_media_attributes_"][id$="_image"]').each(function(){
        var current = $(this);
        var rx = /page_media_attributes_(.*)_image/;
        num = rx.exec(current.attr('id'))[1];
        current.attr('name','page[media_attributes][' + num + '][image]');
    });
});

Of course, this has to be executed on each new dynamically generated element.

So if you go this way, you have to "functionalize" the code above and call it once after document loads for every specific selector you want, and then explicitly for each dynamically added element by cocoon (according to the documentation, special events are fired upon additions/removals).

Lazarus Lazaridis
  • 5,803
  • 2
  • 21
  • 35