Restricting Ruby on Rails Routes with :only and :except
Generating All Routes for a Model
Lets say we have an item
model in a Ruby on Rails application. To create standard routes for this model, we write the following in config.rb
:
|
|
We can run rails routes
to see the routes created by the code above:
|
|
What if we don’t need all of these routes though? We can use :only
and :except
to restrict the routes that are created for a model.
Restricting Routes with :only
If we only need a few routes, it makes sense to use :only
to create only the routes we need. For example, if we only want the index
and show
routes, we can specify them inside an array after only:
:
|
|
This results in only 2 routes being created and we can verify with rails routes
:
|
|
Restricting Routes with :except
:except
works in the opposite way. Instead of specifying the routes we want to create, we specify the ones we don’t want to create.
If we take the example from above and replace only:
with :except
, we can see what happens:
|
|
This time we can see that all routes except for index
and show
were created:
|
|
Restricting a Single Route
Note that if you need to restrict a single route with either :only
or :except
, there is no need to place the route in an array. Write it as a symbol after :only
or :except
like so:
|
|
|
|
References: