LoginSignup
33
32

More than 5 years have passed since last update.

Rails jQueryを用いたajax化のやり方

Posted at

RailsでのajaxをjQueryを用いて実現します。
基本的で分かりやすい削除のajax化を例にしてajax化のやり方を紹介します。

記事(article)の削除のajax化

下記の記事のゴミ箱アイコンを押すと記事がふわっと消えるようにします。

スクリーンショット 2015-05-07 12.39.01.png

まず、ゴミ箱アイコンのリンクにremote: trueを追加します。railsはこれだけでajaxの通信をしてくれます。

article.erb
<%= link_to content_tag(:i, '', class: 'fa fa-trash'), article_path(article.id), method: :delete, data: { confirm: "本当に削除してもよろしいですか" }, class: "article_delete", remote: true %>

ただし、このままだと記事の削除が実行されてデータベース上から消えるだけで画面上からは更新をかけないと消えてくれません。ここからは、ajaxのresponseを受け取り即座に記事を消えるようにします。
controllerでrender :jsonを使いデータをjs側に送ります。

articles_controller.rb
  def destroy
    writer = Article.find(params[:id])['user_id']
    if @user.id != writer
      redirect_to articles_path, :flash => {:alert => "削除権限がありません。"}
    else
      @article.destroy
      render :json => {:article => @article}
    end
  end

ajaxのデータを受け取り、任意の記事を消します。
今回は記事に#item_(id)というidをふっているので、それをfadeOutさせています。

articles.js
(function() {
  $(function() {
    $(document).on('ajax:complete', '.article_delete', function(event, ajax, status) {
      var response;
      response = $.parseJSON(ajax.responseText);
      $('#item_'+response.article.id).fadeOut();
    });
  });
}).call(this);

これで完了です。ゴミ箱アイコンを押すと記事がfadeOutしてくれるはずです。

応用できる

ここでは削除を例にしましたが同様のやり方でいろいろなことをajax化出来そうです。

例えば、commentのcreateのajax化ではformにremote: trueを追加して、コントローラーで部分テンプレートを利用してhtmlを受け取り、あとは同様にajaxで受け取り表示するだけです。

comments_controller.rb
  def create
    @comments = @article.comments.create(comment_params)
      html = render_to_string partial: 'articles/comment_show', locals: { comment: @comments }
      render :json => {:html => html}
  end
33
32
12

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
33
32