Search code examples
ruby-on-railsjquery-select2simple-form

select2 simple_form and initial selected with remote data


I have used simple_form and select2 a bunch on my app and its works fine so far until now.

I have this code:

  <%= f.association :location_from,
    collection: @model.locations,
    label_method: :select_label,
    value_method: :id,
    include_blank: false,
    label: 'From Location',
    class: 'select form-control'
  %>

and my javascript:

$('#pipeline_segment_location_from_id').select2({
  placeholder: 'Select a From Location...',
  allowClear: false,
  multiple: false,
  ajax: {
    url: '/locations/select.json',
    dataType: 'json',
    data: function(params) {
      return {
        'q[loc_cont]': params.term,
        page: params.page
      };
    },
    processResults: function(data) {
      return {
        results: $.map(data, function(item) {
          return {
            text: item.text,
            id: item.id
          };
        })
      };
    }
  }
});

The dropdown works as expected (i.e. ajax etc.). The record saves etc. The issue is when I edit the record again the select is blank and the related record is not loaded into the select. I think I am missing something basic here but I can't seem to figure it out.

UPDATE

I was up way to late working on this. Two issues - I was passing @model.locations which was copied from another unrelated select that was pre-loading the wrong options. All I needed to do was add selected: as per the accepted answer below.

  <%= f.association :location_from,
    selected: @model.location_from_id,
    label_method: :select_label,
    value_method: :id,
    include_blank: false,
    label: 'From Location',
    class: 'select form-control'
  %>

Solution

  • You could pass an extra parameter selected: some_ids. Like

    = f.association :location_from, collection: @model.locations, selected: @record.map(&:location_id), ....