Question

I have a web application running Ruby 2 an Rails 4 and a quite complex form. What I'm trying to do is combine nested forms with chained selects. The problem is that the fields for the nested resource are created on the fly and given a unique combination of date and time, but in my javascript I need to define which select is chained to which other select.

The two tutorials I used for my concept are these: http://homeonrails.blogspot.de/2012/01/rails-31-linked-dropdown-cascading.html http://railscasts.com/episodes/196-nested-model-form-revised

But the important code is basically in three different files:

  $(document).ready(function(){
    $('select#device_name').chainedTo('select#room_name');
  });

This chains one select to another and can be rendered in the form template or the field_partial.

The helper method looks like this:

  def link_to_add_fields(name, f, association)
    new_object = f.object.send(association).klass.new
    id = new_object.object_id
    fields = f.fields_for(association, new_object, child_index: id) do |builder|
      render(association.to_s.singularize + "_fields", f: builder)
    end
    link_to(name, '#', class: "add_fields", data: {id: id, fields: fields.gsub("\n", "")})
  end

And last but not least the coffee script:

jQuery ->
  $('form').on 'click', '.remove_fields', (event) ->
    $(this).prev('input[type=hidden]').val('1')
    $(this).closest('fieldset').hide()
    event.preventDefault()

  $('form').on 'click', '.add_fields', (event) ->
    time = new Date().getTime()
    regexp = new RegExp($(this).data('id'), 'g')
    $(this).before($(this).data('fields').replace(regexp, time))
    event.preventDefault()

So, my understanding of how this works is that I click a button, the helper method creates a new association, gets the id, renders the html from the partial and the coffee script just replaces the id of the object with the current date time, so I can add multiple associations without them having the same id.

The question would be, how to change the javascript of the chained function, to get the ids of the select boxes, because right now I have no idea how to either create a dynamic javascript that would accept the date time from the coffescript or let the javascript search for them and change itself.

Any help or hints would be appreciated!

Was it helpful?

Solution

Huh, the solution was easier as expected. With the following command you can get the child index of the nested resource:

<%= f.object_name.gsub(/[^0-9]+/,'') %>

And this index can be passed into the javascript to chain the two selects to one another:

  $(document).ready(function(){
    $('select#device_attributes_<%= f.object_name.gsub(/[^0-9]+/,'') %>_name').chainedTo('select#room_attributes_<%= f.object_name.gsub(/[^0-9]+/,'') %>_name');
  });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top