Kevin
Kevin

Reputation: 187

How to update/pre-populate Rails form using a dropdown

I am trying to create a form with dropdown where users can create a new object if something like "Create new" is selected, or they have the option of choosing from their previously created objects, which should prefill the form with the corresponding data.

At the moment I simply have a for each loop filling the dropdown list with the previously created objects which is outside the form, and a form that creates new objects.

How can I make this form dynamic so that when a previously selected object is selected, the form pre-fills and allows for editing?

Upvotes: 0

Views: 1032

Answers (2)

Kevin
Kevin

Reputation: 187

So I ended up looping through all of the potential options for the select dropdown, and looping through the edit rails form with all the potential options, and using jQuery onchange to show / hide the correct html.

This doesn't feel like a very good solution to me, especially as it has to load the html of all the options every time.. but I don't know what else to do and it works.

If anyone has any ideas for a better solution, let me know :)

Upvotes: 0

dimitry_n
dimitry_n

Reputation: 3019

You'd have to send out an AJAX GET request to a custom route and then have a controller action that responds to json format and returns a collection based on params passed in that GET request. Say, you are loading available car models based on a selected make:

routes:

get '/get_models/:make_id', to: 'car_makes#available_models'

controller action:

def available_models
  @models = Model.where(id: ids)
  respond_to do |format|
    format.json { render json: @models } 
  end
end 

AJAX request:

var fetchModels = function(makeId){
  $.ajax({
    method: 'GET',
    url:     '/get_models/' + makeId,
    success: function(data) {
      ...
      var target = $('select#car_models');  // field to which options are appended
      $.each(data, function(id, model){
        $(target).append(
          $('<option>').text(model).attr('value', id) // populate options             );
      });
    }
    ...
  });
}

and then setting the AJAX request to fire on .change event in a parent select field:

$('select#car_makes').change(function(){
   var makeId = $(this).val();
   fetchModels(makeId); 
});

There are a number of resources explaining other ways to achieve this:

Upvotes: 1

Related Questions