简体   繁体   English

在Rails 3路由中重命名路径助手

[英]Renaming path helpers in Rails 3 routing

I have a projects controller/model. 我有一个项目控制器/模型。 Instead of listing projects on the #index page, I show a list of drop downs, which submits to projects#select, which finds the right Project (I've made sure there can only be 1 for each combination of options) and forwards the user to the #show page for that Project. 我没有在#index页面上列出项目,而是显示了一个下拉列表,它提交了项目#select,它找到了正确的项目(我确保每个选项组合只能有1个)并转发用户到该项目的#show页面。

So for my routes I do this... 所以对于我的路线,我这样做......

resources :projects, :only => [:index, :show] do
  collection do
    get 'select'
  end
end

And thats fine, but the helper method for #select is 'select_projects', which is understandable but in my case I really want 'select_project'. 这很好,但#select的辅助方法是'select_projects',这是可以理解的,但在我的情况下我真的想要'select_project'。 And I really don't want to alias this in another file. 而且我真的不想在另一个文件中将其别名。 No problem I can use :as... 我可以使用没问题:如......

resources :projects, :only => [:index, :show] do
  collection do
    get 'select', :as => 'select_project'
  end
end

But now my helper is 'select_project_projects'. 但现在我的助手是'select_project_projects'。 So I cheat a little (still better than aliasing in another file)... 所以我作弊一点(仍然比另一个档案中的别名更好)......

resources :projects, :only => [:index, :show]
match '/projects/select', :to => 'projects#select', :as => 'select_project'

This looks like it might work, but it doesn't because /project/select actually matches the route for 'project#show'. 这看起来可能有效,但它并不是因为/ project / select实际匹配'project#show'的路由。 Changing the order of the lines does the trick. 改变线的顺序就可以了。

match '/projects/select', :to => 'projects#select', :as => 'select_project'
resources :projects, :only => [:index, :show]

But is there a more elegant way of handling this? 但有更优雅的方式处理这个? I realize this is borderline OCD, but I'd like to be able to have complete control over the route name within the resources block. 我意识到这是临界OCD,但我希望能够完全控制资源块中的路由名称。

使用资源而不是资源

you probably don't want to make it a collection route but a member route: 你可能不想把它作为收集路线而是成员路线:

resources :projects, :only => [:index, :show] do
  member do
    get 'select'
  end
end

This way you'll have the select_project helper. 这样你就可以得到select_project助手。

对于那些想要重命名辅助方法方面的人(如标题所示):

resources :posts, as: "articles"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM