RESTful なインターフェースを備えた Web アプリケーション(その 5)

いよいよ残る edit, update, destroy を作っていきますが、その前に使いまわしの出来る部分を部分テンプレートにしておきます。

sample/app/views/customers/_customer.html.erb

<tr><th>顧客名</th><td><%= customer.name %></td></tr>
<tr><th>連絡先</th><td><%= customer.phone %></td></tr>

sample/app/views/customers/_form.html.erb

<table>
  <tr>
    <th>顧客名</th>
    <td><%= form.text_field :name, { :size => 20, :required => true } %></td>
  </tr>
  <tr>
    <th>連絡先</th>
    <td><%= form.text_field :phone, { :size => 20, :required => true } %></td>
  </tr>
</table>
<p><%= form.submit button_name, :confirm => 'この内容でよろしいですか ?' %></p>

sample/app/views/customers/_back.html.erb

<p><%= link_to '一覧に戻る', customers_path %></p>

sample/app/views/customers/_msg.html.erb

<p><%= @msg %></p>

部分テンプレートを用いて既存の View を書き変えます。

sample/app/views/customers/show.html.erb

<h1>顧客詳細</h1>
<table border>
  <tr><th>顧客 ID</th><td><%= @customer.id %></td></tr>
  <%= render @customer %>
</table>
<%= render 'back' %>

sample/app/views/customers/new.html.erb

<h1>新規登録</h1>
<%= form_for @customer do |f| %>
<%= render 'form', :form => f, :button_name => '登録' %>
<% end %>
<%= render 'back' %>

(テンプレート適用のほかに、登録時に確認ダイアログを表示させるように変更)

sample/app/views/customers/create.html.erb

<%= render 'msg' %>
<table border>
  <%= render @customer %>
</table>
<%= render 'back' %>

テスト用コードの書き変えも。

sample/test/functional/customers_controller_test.rb

require 'test_helper'

class CustomersControllerTest < ActionController::TestCase
  test "should get index" do
    get :index
    assert_response :success
  end

  test "should get show" do
    get :show
    assert_response :success
  end

  test "should get new" do
    get :new
    assert_response :success
  end

  test "should post create" do
    post :create
    assert_response :success
  end

  test "should get edit" do
    get :edit
    assert_response :success
  end

  test "should put update" do
    put :update
    assert_response :success
  end

  test "should delete destroy" do
    delete :destroy
    assert_response :success
  end
end

とりあえずはここまで。続きは次回に。