【问题标题】:Adding Custom Route to Rails app将自定义路线添加到 Rails 应用程序
【发布时间】:2013-10-16 02:16:03
【问题描述】:

我已经阅读了the Rails Guides

我要设置的是以下路由到“配置文件”控制器:

GET profiles/charities - 应显示所有慈善机构
GET profiles/charties/:id 应显示特定慈善机构
GET profiles/donors - 应显示所有捐赠者
GET profiles/donors/:id - 应显示特定捐赠者

我创建了个人资料控制器和两种方法:慈善机构和捐助者。

这就是我所需要的吗?

【问题讨论】:

  • 我认为你做错了,那些是“子资源”,你需要创建一个慈善机构和捐助者控制器并在你的路由文件中执行一个路由 resource :charities, only: [:index, :show] 或类似的东西,在配置文件中资源

标签: ruby-on-rails routing


【解决方案1】:

以下将为您想要的设置路由,但会将它们映射到CharitiesControllerDonorsController:index:show

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'

以下是您正在阅读的指南中的相关部分:

  1. Resource Routing: the Rails Default - Controller Namespaces and Routing
  2. Non-Resourceful Routes - Naming Routes

【讨论】:

    【解决方案2】:

    慈善机构和捐助者似乎是嵌套资源。如果是这样,在你的 config/routes.rb 文件中你应该有类似的东西,

    resources :profiles do
      resources :charities
      resources :donors
    end
    

    因为这些是嵌套资源,所以您不需要在您的配置文件控制器中使用名为 charities 和donors 的两个方法。事实上,根据您的应用,您可能需要为您的慈善机构和捐赠者提供单独的控制器和/或模型。

    【讨论】:

      猜你喜欢
      • 2011-02-07
      • 1970-01-01
      • 1970-01-01
      • 2022-12-12
      • 2021-08-17
      • 1970-01-01
      • 1970-01-01
      • 2011-07-10
      • 1970-01-01
      相关资源
      最近更新 更多