Search code examples
ruby-on-railsrubynestedcocoon-gem

How to get the index value that forms cocoon?


Need control id (or class) which forms cocoon.
To make custom links work only for the correct elements. To link price is not displayed fill in only the field new_price associated with it.

And I need to get a unique value which forms cocoon.

_promo_service_fields.html.haml

.nested-fields
  %p= f.select :service_id, {}, {}, {class: "service_#{f.index}"}
  %p= f.text_field :new_price
  %p= link_to "price is not displayed", '', remote: true, class: "no-price-#{f.index}"
  %p= link_to_remove_association "Удалить", f

:coffeescript
  $(".service_#{f.index}).ajaxChosen
    # minLength: 3
    dataType: 'json'
    type: 'GET'
    url:'/admin/promo_pages/search_service.json'
    data: {'keyboard':'cat'}

At f.index I get the wrong value (manual)

How can I get a unique value that forms cocoon?


Solution

  • If you check the code, cocoon will only replace the f.index if it is either surrounded with [] or _, which is how it is used in a form when addressing the nested items.

    So the wiki you link to (which I did not write) just happens to work in that specific case because it the f.index is between the square brackets.

    It is a bit unclear what you are trying to do, but there are a few alternatives:

    • use the cocoon callbacks to then fix your code (e.g. assign a unique id based on the order/counter)
    • use jquery selectors which allow to just address/find the nearest/closest selector