2012年9月16日日曜日

Ruby on RailsのRJSを利用したXMLHttpRequestの最小サンプル:その2

XMLHttpRequestを使えるようにRailsが作成したファイルを変更してみる。

▽tests_controller.rb の変更

変更前
  # GET /tests/1
  # GET /tests/1.json
  def show
    @test = Test.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @test }
    end
  end
変更後
  # GET /tests/1
  # GET /tests/1.json
  def show
    @tests = Test.find(:all)
    @test = Test.find(params[:id])
    render

  end
▽show.html.erbの変更

変更前
<p id="notice"><%= notice %></p>

<p>
  <b>Name:</b>
  <%= @test.name %>
</p>


<%= link_to 'Edit', edit_test_path(@test) %> |
<%= link_to 'Back', tests_path %>
変更後
<p id="notice"><%= notice %></p>

<ul id='tests'>
  <%= render({:partial => "test", :collection => @tests}) %>
</ul>

<p>
  <b>Name:</b>
  <span id="test_name">AAAAA</span>
</p>


<%= link_to 'Edit', edit_test_path(@test) %> |
<%= link_to 'Back', tests_path %>
▽_test.html.erbの新規追加
<li><%= link_to test.name, test_path(test)+".js", :remote => true %></li>
▽show.js.erbの新規追加
$("#test_name").html("<%= @test.name %>");
▽サンプルデータの表示の確認

初期状態

クリック後

"XXYYZZ"のリンクをクリックすると、再読み込みなしで、Nameが "XXYYZZ"に変更された。