4

Rails router gives us an easy way to define optional path parameters, like this:

# config/routes.rb
scope "(:locale)", locale: /ru|de|fr/ do
  resources :books
end

Thus we can access /users path and get the default locale, or /ru/books and get the locale in params[:locale].

But with the same setup we can also call the page /books?locale=ru and get the same effect (both path parameters and query string parameters are treated equally and put in the params hash). If locale is processed in a global before_action as Rails i18n guide suggests we can even set locale for the pages that are not supposed to be localized.

So my question is what is the simplest and cleanest way differ path parameters from query string parameters (with the goal to ignore certain query string parameters)?

1 Answer 1

3

Answering my own question:

There is a method ActionDispatch::Request#query_parameters. It returns only the parameters set via query string.

There are also method path_parameters and symbolized_path_parameters. It is obvious they return parameters derived from path (including controller and action). They can be called on request inside a controller action. (They are not documented under ActionDispatch::Request, this is why I missed them initially.)

Rails 5 (edit Jan 9, 2017): As of Rails 5 method symbolized_path_parameters was removed. Method path_parameters is now documented.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.