LoginSignup
1
1

More than 3 years have passed since last update.

RailsのformにAjaxを実装する前提

Posted at

RailsにjQueryを使ったAjaxを適用するために色々調べました。
個人的な備忘録として残します。

configを設定

config/application.rb
require File.expand_path('../boot', __FILE__)

module SampleApp
  class Application < Rails::Application
    config.action_view.embed_authenticity_token_in_remote_forms = true    # 追加
  end
end

コントローラーの変更

class HogesController < ApplicationController
  def hoge
    respond_to do |format|
      format.html redirect_to hoge_path 
      format.js    # ※下
    end
  end
end

※ renderで指定しなければアクション名.js.erbを探す

テンプレートの変更

form_withを使っている場合(推奨)

remoteはデフォルトでtrueのでやることなし
(falseにしたい場合はlocal: trueを追加)

app/view/hoges/hoge.html.erb
<div id="ajax-test">
  <%= form_with ... do |f| %>
    <%= f.submit "hogehoge" %>
  <% end %>
</div>

form_for, form_tagを使っている場合、

オプションにremote: trueを付ける。

app/view/hoges/hoge.html.erb
<div id="ajax-test">
  <%= form_for ..., remote: true do |f| %>
    <%= f.submit "hogehoge" %>
  <% end %>
</div>

コントローラーでrenderしなかった場合、以下の点に注意してファイル.js.erbを追加
・適用したいテンプレートと同じ場所に配置
・ファイル名はコントローラーのアクション名と同じ名前に設定

app/view/hoges/hoge.js.erb
$("#ajax-test").html("<%= 'さあ、遠慮なく私をhogeりなさい!' %>");

記述はjQueryで。

.html("...");の部分を

.html("<%= escape_javascript(render('hoges/hoge')) %>");
.html("<%= j ( render('hoges/hoge') ) %>");でも可
などとすると色々できる。

1
1
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
1
1