3. REST, Resources, and Rails - 3.8 Routing Concerns

3.8 Routing Concerns

One of the fundamental principles Rails developers follow is Don’t Repeat Yourself (DRY). Even though thisis the case, the config/routes.rb file can be prone to having repetition in the form of nested routes that areshared across multiple resources.

resources :auctions do
  resources :bids
  resources :comments
  resources :image_attachments, only: :index
end

resources :bids do 
  resources :comments
end

To eliminate some code duplication and to encapsulate shared behavior across routes, Rails 4 introduces the
routing method concern.

concern :commentable do 
  resources :comments
end

concern :image_attachable do
  resources :image_attachments, only: :index
end

To add a routing concern to a RESTful route, pass the concern to the :concerns option.

# The :concerns option can accept one or more routing concerns.
resources :auctions, concerns: [:commentable, :image_attachable] do 
  resources :bids
end

resources :bids, concerns::commentable

你可能感兴趣的:(3. REST, Resources, and Rails - 3.8 Routing Concerns)