Pages

Saturday, January 4, 2014

Routing Concerns - Rails 4

The Rails config/routes.rb file encapsulates all the mappings from URLs to controller actions. Over the years, helpful additions have been added to slim this file down so that as developers, we can stop repeating ourselves. One example of this was the routing method resources, which maps four named routes to seven controller actions based on the HTTP request method.
As of Rails 4, routing concerns have been added to the router. Routing concerns allows you to declare common routes, which can be mixed into other resources and routes.

Example

A common example of duplication in the config/routes.rb file happens when a polymorphic association is nested under a parent resource.

Here is an example of many resources which also have comments:

The Rails 3 Way

Older::Application.routes.draw do
  resources :projects do
    resources :comments
  end

  resources :tasks do
    resources :comments
  end

  resources :articles do
    resources :comments
  end
end

The Rails 4 Way

Using the routing method concern, we can now define common routes. All routes within a concern will not be included in your routes by default. The concern routes will only be included within a resource by passing it to the routing option:concerns. The :concerns option can accept one or more concerns.

Newer::Application.routes.draw do
  concern :commentable do
    resources :comments
  end

  resources :projects, concerns: :commentable
  resources :tasks, concerns: :commentable
  resources :articles, concerns: :commentable
end

No comments:

Post a Comment