Last Updated: February 25, 2016
·
1.858K
· jakeonrails

Rails two-liner to redirect to url with sorted parameters

This is a good thing to do if your site relies on either a solid SEO strategy, OR if you use page caching which will consider the order of the params for its cache keys.

This works for Rails 3.2+

Older version of Rails will need to replace request#original_url with some other way to get the current full URL.

class ApplicationController < ActionController::Base

 before_filter :ensure_sorted_params

 def ensure_sorted_params
 # url_for(params) in later version of Rails will sort the params.
 sorted_url = url_for(params)

 # request#original_url is only available in Rails 3.2+
 redirect_to sorted_url if request.original_url != sorted_url
 end

end