RailsでのajaxをjQueryを用いて実現します。
基本的で分かりやすい削除のajax化を例にしてajax化のやり方を紹介します。
記事(article)の削除のajax化
下記の記事のゴミ箱アイコンを押すと記事がふわっと消えるようにします。
まず、ゴミ箱アイコンのリンクにremote: trueを追加します。railsはこれだけでajaxの通信をしてくれます。
<%= 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側に送ります。
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させています。
(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で受け取り表示するだけです。
def create
@comments = @article.comments.create(comment_params)
html = render_to_string partial: 'articles/comment_show', locals: { comment: @comments }
render :json => {:html => html}
end