4

I have Rails app, where I'm able to select country from:

= f.input :country, label: t("heading.country"), as: :string, input_html: { class: 'select2', data: { allowadd: true, depth: 0, id: @post.location.country.id, url: search_locations_path } }

Select2 is attached to this element by:

loadSelect2 = (selector = '.select2') ->
  $(@).select2
    ajax:
      data: (term, page) ->
        search: term
        depth: $(@).data('depth')
      results: (data, page) ->
        results: data
      url: $(@).data('url')
    createSearchChoice: (term, data) ->
      if $(data).filter(->
        @title.localeCompare(term) is 0
      ).length is 0
        id: term
        title: term
    createSearchChoicePosition: 'bottom'
    formatResult: (item) ->
      item.title
    formatSelection: (item) ->
      item.title
    initSelection: (element, callback) ->
      callback
        id: $(element).data('id')
        title: $(element).val()

So, as you see, I'm able to select country or add one (if there is no country available). Also I'm loading initial value from input's val and id from data-id inside initSelection.

When I select country and submit the form everything works: post_params['country'] is equal to selected country's id, but if I submit form without changing selected value (leaving the default one), then post_params['country'] helds value, instead of id.

Where am I wrong and how to fix that?

Max Filippov
  • 2,024
  • 18
  • 37

1 Answers1

1

Change your input to:

= f.input :country, label: t("heading.country"), as: :string, input_html: { value: @post.location.country.id, class: 'select2', data: { allowadd: true, depth: 0, title: @post.location.country.title, url: search_locations_path } }

...so that in the input's value you will store id of initially selected element and in data attributes instead of data-id you will store element's title data-title (of course you can leave data-id intact for future use). Also you need to refactor initSelection function to use those new values as of:

initSelection: (element, callback) -> callback id: $(element).val(), title: $(element).data('title')

olhor
  • 948
  • 6
  • 11