如何像在 laravel 中那样在 rails 中 group/nest 路由?

How to group/nest routes in rails like you can in laravel?

我正在从使用 laravel php 框架切换到 rails 框架,无法弄清楚如何让嵌套路由像以前那样在 rails 中工作在 laravel。在 laravel 中它会像这样工作:

Route::group(['prefix' => 'healthandwelness'], function() {

  Route::get('', [
    'uses' => 'healthandwelness@index'
  ]);

  Route::group(['prefix' => 'healthcare'], function() {

    Route::get('', [
      'uses' => 'healthcare@index'
    ]);

    Route::get('{article_id}', [
      'uses' => 'article@index'
    ]);  

  ]);

});

哪个会给我路线:

/healthandwellness
/healthandwellness/healthcare
/healthandwellness/healthcare/{article_id}

我见过在 rails 中嵌套路由的唯一方法是使用我曾经尝试过并在 rails 中重新创建路由的资源,如下所示:

resources :healthandwellness do
  resources :healthcare 
end

但是资源的性质使得这条路线变成了以下的gets:

/healthandwellness
/healthandwellness/:health_and_wellness_id/healthcare
/healthandwellness/:health_and_wellness_id/healthcare/:id

有没有办法做我在 rails 中寻找的东西并重新创建我能够做的 laravel?

您可以使用 namespace:

namespace :healthandwellness do
  resources :healthcare
end

请注意,这假定您的控制器位于 app/controllers/healthsandwellness/healthcare_controller.rb 并且应定义如下:

class Healthandwellness::HealthcareController < ApplicationController
  ...
end

如果你想让你的控制器保持在 apps/controller 下而不是在 app/controllers/healthandwellness 下,你可以使用 scope:

scope '/healthandwellness' do
  resources :healthcare
end

文档 here 提供了 namespacescope

的很好示例