Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Routing concerns defining different param for resources

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.

like image 414
Deepesh Avatar asked Jul 31 '15 09:07

Deepesh


1 Answers

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'}
like image 146
Cyril Duchon-Doris Avatar answered Oct 13 '22 01:10

Cyril Duchon-Doris