Rails + Semantic UIでmultiple select

Rails 5でsemantic-uiのmultipleなselectを使っているときに、初期値としてselectedされた値が表示されずに困っていた。 これはStackoverflowに書いてあった解決策だが、一旦option文のselectedを削除してからsemantic-uiのdropdown関数を呼び出しjavascriptからset selectedして、最後にoption文のseletctedを追加して元に戻しておく、というwalkaroundで解決した。以下に、coffeescript版を掲載しておく。

$(document).on 'ready turbolinks:load', ->
  $('.ui.dropdown').each ->
    $that = $(this)
    values = $that.val()
    $('option', $that).each ->
      $(this).removeAttr 'selected'
      return
    $that.dropdown 'set selected', values
    $('option', $that).each ->
      curr_value = $(this).val()
      i = 0
      while i < values.length
        if values[i] == curr_value
          $(this).attr 'selected', 'selected'
        i++
      return

で、これで解決と言いたいところだが、もう一工夫必要だった。selectedされてない場合はdropdown関数を呼ぶだけにすべき。

$(document).on 'ready turbolinks:load', ->
  $('.ui.dropdown').each ->
    $that = $(this)
    if $that.attr('multiple') && $('option[selected]', $that).length > 0
      values = $that.val()
      $('option', $that).each ->
        $(this).removeAttr 'selected'
      $that.dropdown 'set selected', values
      $('option', $that).each ->
        curr_value = $(this).val()
        i = 0
        while i < values.length
          if values[i] == curr_value
            $(this).attr 'selected', 'selected'
          i++
    else
      $(this).dropdown()

参考 jquery - Semantic UI: Multi Select Dropdown pre-select values - Stack Overflow