Rails Routes - How to make them case insensitive?

安稳与你 提交于 2019-12-01 15:40:51
Carsten Gehling

I've just has the same problem, and solved it using middleware - have a look here:

http://gehling.dk/2010/02/how-to-make-rails-routing-case-insensitive/

Note: This only applies for Rails 2.3+

  • Carsten

Routes in Rails are case sensitive because URLs are case sensitive. From the W3C:

URLs in general are case-sensitive (with the exception of machine names). There may be URLs, or parts of URLs, where case doesn't matter, but identifying these may not be easy. Users should always consider that URLs are case-sensitive.

Well you could try another approach. Make the case transform serverside and send everything to rails downcase.

I think you can achieve this with either mod_rewrite or mod_spelling.

bitemerailsboys

just monkey-patch it to downcase by default. simple example:

module ActionController
  module Caching
    module Pages
      def cache_page(content = nil, options = nil)
        return unless perform_caching && caching_allowed

        path = case options
          when Hash
            url_for(options.merge(:only_path => true, :skip_relative_url_root => true, :format => params[:format]))
          when String
            options
          else
            request.path
        end

        path = path.downcase

        self.class.cache_page(content || response.body, path)
      end
    end
  end
end

A simple solution is, may be not an elegant way, but yet workable is: Use a before_filter in your application controller like this.

  before_filter :validate_case

  def validate_case
    if request.url != request.url.downcase
      redirect_301_permanent_to request.url.downcase
    end
  end

  def redirect_301_permanent_to(url)
     redirect_to url, :status=>:moved_permanently 
  end

As i already told that its not an elegant but yet workable, so no down votes please. :P

Though URLs are case-sensitive, if you want to make your routes case-insensitive, there is a dirty hack you can do.

In application_controller.rb put:

rescue_from ActionController::RoutingError do |exception|
 redirect_to request.url.downcase
end

But don't actually do that. You create a redirect loop for any non-existant routes. You really should parse request.request_uri into its components, downcase them, and use them to generate the legit route that you redirect to. As I mentioned right off, this is a dirty hack. However, I think this is better than making your route map ugly and hackish.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!