user3479760
user3479760

Reputation: 1

How to define routing concern in rails

How to define rails route concern

I have attachment for user and message. how can i defined common route

resources :comments

Routes for user and message controller

resources :users
resources :messages

Upvotes: 0

Views: 1363

Answers (2)

Aaditi Jain
Aaditi Jain

Reputation: 7027

As far as I understand your question you have a attachment for both user and message and need a more DRY way of creating routes for this. We can use concerns for this purpose.

concern :attachable do
  resource: :attachment #singular routes
end

resources :users, :messages, concerns: :attachable

I have used singular routes as I assume there is a has_one relationship between attachment and user/message. That is, user has_one attachment or message has_one attachment. If its a has_many relationship, use plural routes ie

resources: :attachments

Upvotes: 2

Richard Peck
Richard Peck

Reputation: 76774

According to documentation, you'll need:

#config/routes.rb
concern :attachment do
  resources :attachment, only: :index
end

resources :users, :messages, concerns: :attachment

Upvotes: 1

Related Questions