hamayuzinの日記

エンジニアとかデータサイエンティストとかやってます。あの時 あれやってたな的な備忘録にできれば。

【Rails/Bootstrap/modal】rails bootstrapのmodalをajaxで操作する

とあるアーティストの曲を取得したい場合を考える  「曲の一覧」というリンクをクリックすると そのアーティストの一覧を取得して、曲の一覧をモーダルで出す。

index.haml:曲の一覧を表示する

%a.open_modal{disable: true, id: @artist.id}
  曲の一覧

- content_for :modal do
  = render 'modal'

- @content_for_javascript = capture do
  = javascript_include_tag "open_moadl"

application.haml:モーダルを読み込むようのyieldを追記

= yield :modal

artists_controller.rb:ajaxで叩かれるURLを追加

def show_songs
    respond_to do |format|
      songs = Artist.find(params[:artist_id]).songs
      format.json { render json: { songs: songs } }
    end
end

open_moadl.coffee:クリック時にajaxを呼び、返ってきた結果を追加して、modalを表示する + 閉じるボタンで閉じる挙動

$ ->
   $(".open-modal").click ->
    $.ajax
      async: true
      type: "GET"
      url: '/artists/show_songs.json'
      dataType: 'json'
      data: {
        artist_id: $(this)[0].id;
      }
      success: (result, status, xhr) ->
        $.each result['songs'], ->
          console.log(this)
          if this
            $('#songs_table').append('<tr><td>' + this['name'] + "</td><td>" + this['year'] + '</td></tr>')
        $("#songs-modal").modal()

  $(".close-songs-modal").click ->
    $("#songs-modal").modal("hide")

_moadl.haml:モーダルの画面イメージ

#ongs-modal.modal.fade{tabindex: "-1"}
  .modal-dialog.modal-lg{role: "document"}
    .modal-content
      .modal-header
        %h3
      .modal-body
        .col-md-12
          %table.table.table-striped.table-bordered.ma-top-10#songs_table
            %thead
              %tr
                %th.ta-center 曲名
                %th.ta-center 発売年
            %tbody
      .modal-footer
        %button.btn.btn-primary.close-promotion-modal 閉じる