LoginSignup
31
32

More than 5 years have passed since last update.

ajax_render gemを使ってrailsのajaxを楽に実装する

Last updated at Posted at 2013-12-22

ajax_render gem

railsでajax実装するのちょっとめんどくさいなと思っていたのでajax_renderというgemをつくりました。

普通のajax実装

# config/routes.rb
Dummy::Application.routes.draw do
  resource :test, only: [:index] do
    member do
      post :ajax
    end
  end
end
# app/controllers/tests_controller.rb
class TestsController < ApplicationController
  def index
  end

  def ajax
    @value = params[:id]
    respond_to do |format|
      format.js
    end
  end
end
-# app/views/tests/index.html.haml
.document
  %p some content
  .partial
    Loading ...
-# app/views/tests/ajax.js.haml
:plain
  $(".partial").html(
    "#{escape_javascript(render '/tests/partial', locals: { value: @value })}"
  );
-# app/views/tests/_partial.html.haml
partial content: #{value}
# app/assets/javascripts/test.js.coffee
jQuery ($) ->
  id = 100
  $.post('/tests/ajax', {"id": id})

こうなりますね

実装するのがこれだけならいいですが、たくさんajaxな処理を実装したい場合は結構大変です。

ajax_renderを使う

そこで、ajax_render gemを使ってtests_controller.rbajax.js.hamlの実装を簡略化します。

# Gemfile
gem 'ajax_render'
# app/controllers/tests_controller.rb
class TestsController < ApplicationController
  def index
  end

  def ajax
    ajax_render '/test/partial', replace: '.partial', locals: { value: params[:id] }
  end
end
-# app/views/tests/ajax.js.haml
-# 不要!

ajax_renderがajax.js.hamlみたいなのをrenderしてくれるのでajax.js.hamlは不要になります。
これで実装するのが楽になりました。是非ご活用ください。

31
32
0

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
31
32