Techioz Blog

Rails ルーティング: パス ヘルパーにデフォルト値を与える

概要

URL/パスヘルパーにデフォルト値を提供する方法はありますか?

すべてのルートをラップするオプションのスコープがあります。

#config/routes.rb
Foo::Application.routes.draw do

  scope "(:current_brand)", :constraints => { :current_brand => /(foo)|(bar)/ } do
    # ... all other routes go here
  end

end

ユーザーが次の URL を使用してサイトにアクセスできるようにしたいと考えています。

/foo/some-place
/bar/some-place
/some-place

便宜上、ApplicationController に @current_brand を設定しています。

# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  before_filter :set_brand

  def set_brand                                                                 
    if params.has_key?(:current_brand)                                          
      @current_brand = Brand.find_by_slug(params[:current_brand])               
    else                                                                        
      @current_brand = Brand.find_by_slug('blah')
    end
  end

 end

ここまではうまくいきましたが、ここですべての *_path 呼び出しと *_url 呼び出しを変更して、:current_brand パラメーター (オプションであっても) を含める必要があります。これは本当に醜いです、私の意見では。

パスヘルパーが @current_brand を自動的に取得できるようにする方法はありますか?

それとも、routes.rb でスコープを定義するより良い方法でしょうか?

解決策

次のようなことをしたいと思うでしょう:

class ApplicationController < ActionController::Base

  def url_options
    { :current_brand => @current_brand }.merge(super)
  end

end

このメソッドは、URL が構築されるたびに自動的に呼び出され、その結果がパラメータにマージされます。

これについて詳しくは、default_url_options と Rails 3 を参照してください。