You'll need to reinitialize the second select2 element after you receive the data result from the first select2's ajax call. Something like this should work:
firstSelection = $('#first_id').select2( allowClear: false )
secondSelection = $('#second_id')
firstSelection.on('select2-selecting', (e)->
if e.val
$.get(
"/api/v1/posts/#{e.val}",
(data)-> (
console.log data
newOptions = data
select = secondSelection
if select.prop
options = select.prop("options")
else
options = select.attr("options")
$("option", select).remove()
$.each newOptions, (val, text) ->
options[options.length] = new Option(text, val)
secondSelection.select2()
)
)
)
The basic mechanics are to create option
s from your data, add them to the secondSelection
element, and then initialize select2 again on that element.