Ruby-on-rails 将自定义路由添加到 Rails 应用程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19394192/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding Custom Route to Rails app
提问by Sriram Venkatesh
I have read up on the Rails Guides.
我已经阅读了Rails 指南。
What I want to set up are the following routes that are routed to the 'profiles' controller:
我要设置的是以下路由到“配置文件”控制器的路由:
GET profiles/charities- Should display all the charitiesGET profiles/charties/:idshould display a specfic charityGET profiles/donors- Should display all the donorsGET profiles/donors/:id- Should display a specfic donor
GET profiles/charities- 应显示所有慈善机构GET profiles/charties/:id应显示特定慈善机构GET profiles/donors- 应显示所有捐赠者GET profiles/donors/:id- 应显示特定捐赠者
I have created the profile controller and two methods: charities and donors.
我创建了配置文件控制器和两种方法:慈善机构和捐助者。
Is this all I need?
这就是我所需要的吗?
回答by kristinalim
The following will set up routes for what you want, but will map them to :indexand :showof CharitiesControllerand DonorsController:
以下将设置您想要的路由,但会将它们映射到:indexand :showof CharitiesControllerand DonorsController:
namespace :profiles do
# Actions: charities#index and charities#show
resources :charities, :only => [:index, :show]
# Actions: donors#index and donors#show
resources :donors, :only => [:index, :show]
end
When it's more appropriate to set up custom routes, something like this would do:
当设置自定义路由更合适时,可以这样做:
get 'profiles/charities', :to => 'profiles#charities_index'
get 'profiles/charities/:id', :to => 'profiles#charities_show'
get 'profiles/donors', :to => 'profiles#donor_index'
get 'profiles/donors/:id', :to => 'profiles#donor_show'
Here are relevant sections in the guide that you were going through:
以下是您正在阅读的指南中的相关部分:
回答by Chris Jeon
The charities and donors seem to be nested resources. If so, in your config/routes.rb file you should have something like,
慈善机构和捐助者似乎是嵌套的资源。如果是这样,在你的 config/routes.rb 文件中你应该有类似的东西,
resources :profiles do
resources :charities
resources :donors
end
Because these are nested resources, you do not need the two methods named charities and donors in your profiles controller. In fact, depending on your app, you may need separate controllers and/or models for your charities and donors.
因为这些是嵌套资源,所以您不需要配置文件控制器中名为 charities 和donors 的两个方法。事实上,根据您的应用程序,您可能需要为您的慈善机构和捐助者提供单独的控制器和/或模型。

