Ruby on Rails ステップ・バイ・ステップ
STEP 14: 確認画面(4)
STEP 11-13で行ったことをタスクを編集する場合についても行って、「確認画面」の実装を終わりにしましょう。
ルーティングを修正します。
$ edit config/routes.rb
ActionController::Routing::Routes.draw do |map|
map.root :controller => 'top', :action => 'index'
map.resources :tasks,
:new => { :new => :post },
:member => { :simple => :get, :finish => :put, :edit => :put, :confirm => :put },
:collection => { :unfinished => :get, :confirm => :post }
end
:member オプションに要素 :edit => :put と :confirm => :put を追加しています。
edit アクションのテンプレートを修正します。
$ edit app/views/tasks/edit.html.erb
<h1>タスクの編集</h1>
<% form_for [ :confirm, @task ] do |f| %>
<%= render :partial => 'form', :locals => { :f => f } %>
<% end %>
$ edit app/views/tasks/_form.html.erb
(省略) <div class="buttonGroup"> <input type="button" value="戻る" disabled="disabled" /> <%= f.submit '次へ' %> </div>
confirm アクションを修正します。
$ edit app/controllers/tasks_controller.rb
def confirm
if request.post?
@task = Task.new(params[:task])
else
@task = Task.find(params[:id])
@task.attributes = params[:task]
end
if @task.valid?
render :action => 'confirm'
else
render :action => request.post? ? 'new' : 'edit'
end
end
end
部分テンプレート button_to_back を修正します。
$ edit app/views/tasks/_button_to_back.html.erb
<% form_for(@task, :url => @task.new_record? ? [ :new, :task ] : [ :edit, @task ]) do |f| %>
<% [ :subject, :due_date, :done, :note ].each do |attr| %>
<%= f.hidden_field attr %>
<% end %>
<%= f.submit '戻る' %>
<% end %>
edit アクションを修正します。
$ edit app/controllers/tasks_controller.rb
def edit
@task = Task.find(params[:id])
@task.attributes = params[:task] if request.put?
end
end
ブラウザで動作を確認します。

「次へ」ボタンをクリックします。

「戻る」ボタンをクリックすると…

一応、これで「確認画面」は完成です。
(2010/02/26)
記事に関するご質問は、 hermes@oiax.jp までメールでお送りください。
ウェブサイト構築の発注先を検討されているお客様は、ご相談フォームをご利用ください。
- はじめに
- STEP 1: アプリケーションの作成からトップページの表示まで (2010/01/26)
- STEP 2: レイアウト (2010/01/27)
- STEP 3: レコードの一覧 (2010/01/29)
- STEP 4: レコードの詳細表示と削除 (2010/01/30)
- STEP 5: レコードの新規追加 (2010/02/01)
- STEP 6: レコードの編集 (2010/02/02)
- STEP 7: 基本7アクション (2010/02/02)
- STEP 8: 未完了タスクの一覧 (2010/02/03)
- STEP 9: タスクの簡易表示 (2010/02/12)
- STEP 10: finishアクションの実装 (2010/02/13)
- STEP 11: 確認画面(1) (2010/02/14)
- STEP 12: 確認画面(2) (2010/02/25)
- STEP 13: 確認画面(3) (2010/02/25)
- STEP 14: 確認画面(4) (2010/02/26)

