Rails: Accessing route segment defaults

311 views Asked by At

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

1

There are 1 answers

1
deefour On BEST ANSWER

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"