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.rb
とajax.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
は不要になります。
これで実装するのが楽になりました。是非ご活用ください。