AjaxでRedirect

(注)動作確認はRails 2.0.1
小ネタですが少し引っかかってしまったので参考まで。Ajaxは画面遷移を伴わないので、例えばデータ作成が成功したら詳細画面に飛ぶような処理をしたい場合、サーバからURLを渡してクライアント側で遷移する処理(location.href)を書きます。以下サンプル。

Controller

class HogeController < ApplicationController
  def index
    @hoge = Hoge.new
  end

  def create
    hoge = Hoge.new(params[:hoge])
    if hoge.save
      render :text => url_for(:action => "show", :id => hoge.id)
    else
      render :text => hoge.errors.full_messages.join("\n"), :status => 500
    end
  rescue
    render :text => "作成に失敗しました。", :status => 500
  end

  def show
    @hoge = Hoge.find(params[:id])
  end
end

View

<% form_remote_for( 
  :hoge, @hoge,
  :url=>{:action=>"create"},
  :confirm => "ホゲを登録します。よろしいですか?",
  :success => "location.href = request.responseText;",
  :failure => "alert(request.responseText);"
) do |f| %>
(略)
<% end %>