Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: The easiest way to differ path parameter from query string parameter?

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)?

like image 811
khustochka Avatar asked Oct 20 '25 10:10

khustochka


1 Answers

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.

like image 190
khustochka Avatar answered Oct 22 '25 00:10

khustochka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!