Logo lr 1c3bec71c7d53d0051ed754194e6408a12981dd23dde1cd852b3c8f718c40b5b

Using with_options on Routes

clean up a group of resources with the same allowed actions

Using with_options on Routes

Why should you use #with_options?

The problem #with_options solves is subtle. When we have a list of method calls that each have the same options in their arguments, then this technique can make your code more expressive.

For example, when defining actions in our routes.rb file, we often have a lit of routes with the same options (i.e. when we only want the index route).


resources :lions, only: :index
resources :tigers, only: :index
resources :bears, only: :index

This is fine, however, we could use #with_options


with_options only: :index do |list_only|
  list_only.resources :lions
  list_only.resources :tigers
  list_only.resources :bears

Our argument 'only: :index' is being passed to the end of each method call. As you can see this technique requires more code. However, one benefit you get, is that it is much easier to tell at first glance that only :index applies to the list of resources. It is even more obvious in a larger app with many resources.

Choose the option that best expresses your code.