0

I would like to access the defaults I define for a specific route. But Rails refuses to put it into the params hash. Example:

routes.rb:

get "packages(/:display)", to: "packages#index", defaults: { display: 'grid' }

URL that I call:

http://localhost:3000/packages

The params hash becomes:

{"action"=>"index", "controller"=>"packages"}

But what I would prefer is to get:

{"action"=>"index", "controller"=>"packages", "display"=>"grid"}

The problem is no biggy really. But Rails claims to by DRY so that I thought I could keep the defaults in the routes.rb and not repeat them in my controller or view code.

My intention is to display either a grid of results or list of results. And if the user does not specify a certain view I would like to use the grid-style.

(I'm using Rails 4.)

  • Do you have an earlier route that `/packages` is matching? – deefour Sep 04 '13 at 21:06
  • Oh my. You guessed so right. get "packages" => "packages#index". I commented it out and now the default parameter is passed as expected. Thanks so much for looking into your crystal ball. :) – Christoph Haas Sep 04 '13 at 21:27
  • Although I get a pretty strange effect now when I call /packages/list. I assumed that *params* is the same as *request.params*. But *params* is {"display"=>"grid", "controller"=>"packages", "action"=>"index"} while *request.params* is {"display"=>"list", "controller"=>"packages", "action"=>"index"}. Weird. – Christoph Haas Sep 04 '13 at 21:37

1 Answers1

0

I have just tested the following route in my Rails 4 app.

get "packages(/:display)", to: "packages#index", defaults: { display: "grid" }
  • /packages: params[:display] is "grid"
  • /packages/list: params[:display] is "list"

It's likely you have other routes playing into this still, preventing the same results I lay out above.

Short of finding such conflicts, how about we avoid the optional segment (the result is the same as above)?

get "packages",          to: "packages#index", display: "grid"
get "packages/:display", to: "packages#index"
deefour
  • 34,974
  • 7
  • 97
  • 90
  • Thank you. Makes me think indeed. Seems I'm putting too much effort into URL segments when I should rather use multiple routes to make it more explicit. I will try this. However I'm still confused why *params* and *request.params* give me different results. – Christoph Haas Sep 05 '13 at 09:41