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?