7

Recently I got to know about rails concerns in routes from this discussion How to have one resource in routes for namespace and root path altogether - Rails 4. Now in my application I have routes like this:

namespace :admin do
  resources :photos
  resources :businesses
  resources :projects
  resources :quotes
end
resources :photos, param: 'slug'
resources :businesses, param: 'slug' do
  resources :projects, param: 'slug' #As I need both the url one inside business and one outside
end
resources :projects, param: 'slug'
resources :quotes, param: 'slug'

And there are many more resources which are repeating as I needed them. I know about concerns how to implement them. With the concerns I can do it like this:

concern :shared_resources do
  resources :photos
  resources :businesses
  resources :projects
  resources :quotes
end
namespace :admin do
  concerns :shared_resources
end
concerns :shared_resources

but how can I give different param each time in the concerns? I tried doing it like this:

concerns :shared_resources, param: 'slug'

But this brings no change in the routes. And if I add:

resources :photos, param: 'slug'

Then it will add to both the routes slug instead of id. But in admin side I need id and in front end I need slug. So are there any options to pass this in the concerns so to DRY up the code.

Community
  • 1
  • 1
Deepesh
  • 6,138
  • 1
  • 24
  • 41

1 Answers1

6

Yes I remembered seeing something about this. It wasn't in the Rails guide, but an answer to a SO question that kinda surprised me. You can use a block : (quoted from the aforementionned answer)

In Rails 4 you can pass options to concerns. So if you do this:

# routes.rb
concern :commentable do |options|
  resources :comments, options
end

resources :articles do
  concerns :commentable, commentable_param: 'slug'
end

Then when you rake routes, you will see you get a route like

POST /articles/:id/comments, {commentable_param: 'slug'}
Community
  • 1
  • 1
Cyril Duchon-Doris
  • 12,964
  • 9
  • 77
  • 164
  • Thanks for the reply but unfortunately this didn't work I didn't find any changes. Have you ever tried this? Means if this worked for you. – Deepesh Aug 01 '15 at 10:00
  • Hmm I wasn't sure of this, but in the question I linked they have used parameters that looked like `${concern_name}_something`. Can you try with this syntax if it works ? To be honest I didn't try it myself but given the upvotes of the answer I thought it'd work... – Cyril Duchon-Doris Aug 01 '15 at 12:33