read

Rails routes can be customized to include your own parameters inside it. Lets first understand how named routes works:

Adding dynamic parameters to routes

Here exact parameters are matched to route and presence of each parameter is mandatory in order to construct urls. If blank parameter is supplied then it will raise RoutingError exception.

Exact matched named route declared as :

match ':a/:b/:c', :to => 'home#index', :as => :q

rails console :

app.q_url(:a, :b, :c)
#=> "http://www.example.com/a/b/c"
app.q_url(:a, :b, '')
#=> ActionController::RoutingError: No route matches {:controller=>"home", :a=>:a, :b=>:b, :c=>""}

## Bound parameters to named routes
If you are sure that certain parameters can be blank then you can define them as optional parameter inside route

match ':a/:b(/:c)', :to => 'home#index', :as => :q

rails console :

app.q_url(:a, :b, '')
#=> "http://www.example.com/a/b?c="
app.q_url(:a, :b)
#=> "http://www.example.com/a/b"
Blog Logo

Sandip Ransing


Published

Image

Fun On Rails

Journal of a Web Developer #ruby #rails #JS

Back to Overview