添加自定义路由到Rails应用程序
我已经阅读了Rails指南 。
我想要设置的是以下路由到路由到’profiles’控制器:
GET profiles/charities
– 应显示所有慈善机构
GET profiles/charties/:id
应该显示一个特定的慈善机构
GET profiles/donors
– 应显示所有捐赠者
GET profiles/donors/:id
– 应该显示一个特定的捐赠者
我创建了配置文件控制器和两种方法:慈善机构和捐赠者。
这就是我需要的吗?
以下将根据您的需要设置路由,但会将它们映射到:index
和:show
of CharitiesController
和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
如果更适合设置自定义路由,这样的事情会:
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'
以下是您正在阅读的指南中的相关章节:
- 资源路由:Rails默认 – 控制器命名空间和路由
- 非资源路由 – 命名路由
慈善机构和捐赠者似乎是嵌套资源。 如果是这样,在你的config / routes.rb文件中你应该有类似的东西,
resources :profiles do resources :charities resources :donors end
因为这些是嵌套资源,所以在配置文件控制器中不需要名为charities和donor的两个方法。 事实上,根据您的应用程序,您可能需要为您的慈善机构和捐赠者提供单独的控制器和/或模型。