Tuesday 16 September 2014

Concerns in Rails Part 2 : Using concerns in Routes

With Rails 4, the concept of using concerns has been in highlights. Concerns can be used in routing to DRY up your routes.rb file.
Consider the following example: Consider an Events, a Articles, a Photos and a Comments controller. A event , photo and a article has_many comments. A comment belongs_to either a event, a article or a photo.
Typically, the route.rb file will have nested resourcing and may look like this:
  Rails.application.routes.draw do
      resources :events do
         resources :comments
     end
      resources :articles do
         resources :comments
     end
     resources :photos  do
         resources :comments
     end
   end
Using Concerns you can DRY up you routes.rb  as shown below:

 Rails.application.routes.draw do
   concern :commentable do
     resources :comments
   end
   resources :articles,events, photos, concerns: :commentable 
 end

No comments:

Post a Comment