路由关注点定义了资源的不同参数 [英] Routing concerns defining different param for resources
问题描述
最近我从这次讨论中了解了路线中的铁轨问题
如何在路由中为命名空间和根路径完全使用一种资源-Rails 4 。现在在我的应用程序中,我有这样的路由:
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
但是我如何每次都给不同的 param
担心吗?我尝试这样做:
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'
然后它将添加到两条路由段中,而不是id中。但是在管理方面,我需要ID,在前端,我需要塞子。因此,有没有其他方法可以解决此问题,以便使代码干燥。
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.
推荐答案
是的,我记得我曾对此有所了解。它不在Rails指南中,但是一个SO问题的答案令我有些惊讶。您可以使用一个block :(从上述答案中引用)
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)
在Rails 4中,您可以将选项传递给关注点。因此,如果您这样做:
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'}
这篇关于路由关注点定义了资源的不同参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!