Search code examples
ruby-on-railsrubyruby-on-rails-5

Ruby On Rails - Use "Format" As A URL GET Parameter?


I have a search page where I update the URL params on the page as filters are added or removed by the user. This allows me to deep link into the page (ie. going to /search?location=new+york&time=afternoon will set the location and afternoon filters).

I also have a filter named format. I noticed that passing in ?format=whatevervalue to the URL and then reloading the page with that param causes Rails to return a Completed 406 Not Acceptable error. It seems that format is a reserved Rails URL parameter.

Is there anyway to unreserve this parameter name for a particular endpoint?


Solution

  • In the context of a URL in Ruby on Rails there are at least five reserved parameter names: method, controller, action, id, format.

    You cannot use these keys for anything else than for their intended purpose.

    If you try to, you will override the value internally set by Rails. In your example, by setting ?format=whatevervalue you override the default format (html) and your application will try to find and render a whatevervalue template instead of the html formatted template. This will obviously not work.

    Fun fact: Instead of using the default Rails path format like /users/123/edit you could use query parameters instead like this: /?controller=users&id=123&action=edit&format&html.

    My suggestion is: Do not try to fight Rails conventions. Whenever you try to work around basic Rails conventions it will hurt you later on because it makes updates more difficult, common gems might break, unexpected side effects will happen. Just use another name for that parameter.