Routing concerns defining different param for resources

天大地大妈咪最大 提交于 2020-01-01 10:48:13

问题


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.


回答1:


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'}


来源:https://stackoverflow.com/questions/31742416/routing-concerns-defining-different-param-for-resources

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!