Rails 6 routes - 简单嵌套路由的正确方法

Rails 6 routes - proper way of simple nesting routes

因为我使用 Rails 单体而不是 GrapeAPI 已经有一段时间了,所以我提出了一个愚蠢的问题。我想为路径创建一个路由 - users/portfolios/1/portfolio_reports/archived_reports 我将在其中显示 PortfolioReports.where(status: 'archived')。我创建了路线:

  namespace :users do
    resources :portfolios, only: [:index, :show] do
      resources :archived_report, only: [:index, :show]
      resources :portfolio_report, only: [:index, :show]
    end
  end

所以我有两个问题:路由文件应该像我当前的 routes.rb 吗?如果我有像下面这样的 Portfolio 和 PortfolioReport 模型,portfolio_reports_controller 应该在 app/controllers/users/portfolio_reports_controller.rbapp/controllers/portfolio_reports_controller.rb ?

  class Portfolio
    has_many :portfolio_reports
  end

  class PortfolioReport
    belongs_to :portfolio
  end

在 Rails 中,您可以使用“浅嵌套”,它基本上表示仅将 indexnewcreate 操作嵌套在父资源下。对于其他操作,您不需要嵌套路由,因为通过记录本身您可以访问关联的记录,因此不需要在 url.

中包含 id

因此您的路线将是:

users/portfolios/                    # Portfolios#index
users/portfolios/1                   # Portfolios#show
users/portfolios/1/portfolio_reports # PortfolioReports#index
users/portfolio_reports/1            # PortfolioReports#show
users/portfolios/1/archived_reports  # ArchivedReports#index
users/archived_reports/1             # ArchivedReports#show

而 routes.rb 应该是这样的:

namespace :users do
  resources :portfolios, only: [:index, :show] do
    resources :archived_report, only: [:index]
    resources :portfolio_report, only: [:index]
  end
  resources :archived_report, only: [:show]
  resources :portfolio_report, only: [:show]
  end

(如果您要使用所有 7 条路线,您可以使用文档中提到的助手 shallow)。 无需像您在问题中提到的那样将 archived_reports 嵌套在 portfolio_reports 下!

在此处查找有关浅嵌套的更多信息:https://guides.rubyonrails.org/routing.html#shallow-nesting

对于 user 命名空间: 您的控制器应该位于子文件夹 user 中,因为您拥有命名空间 user:

app/controllers/user/portfolio_reports_controller.rb