URL末尾のスラッシュ / でアクションを変える
Rails 1.2.5
/hello で HelloController#index、/hello/ で HellController#slash を呼びたいが、routes.rb に
ActionController::Routing::Routes.draw do |map| map.connect 'hello/', :controller => 'hello', :action => 'slash' map.connect 'hello', :controller => 'hello', :action => 'index' end
と書くとすべて index アクションに飛ばされてしまう。のでいじる。
/app/controllers/hello_controller.rb
class Report::PageController < ReportController def index end def slash end protected def perform_action_with_slash @action_name = 'slash' if request && request.path == '/hello/' perform_action_without_slash end alias_method_chain :perform_action, :slash end
url_for(:controller => 'hello', :action => 'slash') もうまくいかないのでいじる。
/app/controllers/application.rb
class ApplicationController < ActionController::Base def url_for_with_slash(options = {}, *parameters_for_method_reference) if options.is_a? Hash controller = options[:controller] || controller_name action = options[:action] || action_name if controller == 'hello' && action == 'slash' return url_for_without_slash(options, *parameters_for_method_reference).sub(/([^\/])(\?|$)/, '\1/\2') end end url_for_without_slash(options, *parameters_for_method_reference) end alias_method_chain :url_for, :slash end
せぱれーたーなんたらを設定すればいいかと思ったんだけど、うまくいかないのでそのばしのぎ