Rails 6 raises ArgumentError if param contains colon

Amit Choudhary

Amit Choudhary

October 15, 2019

This blog is part of our  Rails 6 series.

The :param option in routes is used to override default resource identifier i.e. :id.

Let's take for an example that we want product :name to be as the default resource identifier instead of :id while defining routes for products. In this case, :param option comes handy. We will see below how we can use this option.

Before Rails 6, if resource custom param contains a colon, Rails used to consider that as an extra param which should not be the case because it sneaks in an extra param.

An issue was raised in Aug, 2017 which was later fixed in February this year.

So, now Rails 6 raises ArgumentError if a resource custom param contains a colon(:).

Let's checkout how it works.

Rails 5.2

Let's create routes for products with custom param as name/:pzn.

1
2> > Rails.application.routes.draw do
3> > resources :products, param: 'name/:pzn'
4> > end
5> >
1\$ rake routes | grep products
2products GET /products(.:format) products#index
3POST /products(.:format) products#create
4new_product GET /products/new(.:format) products#new
5edit_product GET /products/:name/:pzn/edit(.:format) products#edit
6product GET /products/:name/:pzn(.:format) products#show
7PATCH /products/:name/:pzn(.:format) products#update
8PUT /products/:name/:pzn(.:format) products#update
9DELETE /products/:name/:pzn(.:format) products#destroy

As we can see, Rails also considers :pzn as a parameter.

Now let's see how it works in Rails 6.

Rails 6.0.0.rc1

1
2> > Rails.application.routes.draw do
3> > resources :products, param: 'name/:pzn'
4> > end
5> >
1\$ rake routes | grep products
2
3rake aborted!
4ArgumentError: :param option can't contain colons
5/Users/amit/.rvm/gems/ruby-2.6.3/gems/actionpack-6.0.0.rc1/lib/action_dispatch/routing/mapper.rb:1149:in `initialize' /Users/amit/.rvm/gems/ruby-2.6.3/gems/actionpack-6.0.0.rc1/lib/action_dispatch/routing/mapper.rb:1472:in `new'
6/Users/amit/.rvm/gems/ruby-2.6.3/gems/actionpack-6.0.0.rc1/lib/action_dispatch/routing/mapper.rb:1472:in `block in resources'
7...
8...
9...

Here is the relevant issue and the pull request.

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.