Ruby 在 Rails - 控制器子目录

Ruby on Rails - Controller Subdirectory

我对 RoR 有点陌生,

我想要一个结构化的目录,因为项目可能会变大我不想让所有的控制器直接进入controllers目录。

我想要

app/
    controllers/
          application_controller.rb
          groupa/
                athing_controller.rb
                athing2_controller.rb
          groupb/
                bthing_controller.rb

然而,当我在 routes.rb 中放置以下内容时:

get 'athing', :to => "groupa/athing#index"

我在 localhost:3000/athing/ 上收到以下错误:

superclass mismatch for class AthingController

这就像:

class AthingController < ApplicationController
  def index
  end
end

我错过了什么吗? 我可以放置子目录吗?

尝试改用命名空间:

在你的路线中:

namespace :groupa do
  get 'athing', :to => "athing#index"
end

在你的控制器中:

class Groupa::AthingController < ApplicationController

在浏览器中:

localhost:3000/groupa/athing/

在config/routes.rb

namespace :namespace_name do
  resources : resource_name
end

在app/controllers/

用你的 namespace_name 创建一个模块名称,在那个地方你的控制器 在那个控制器中 class 名字应该是这样的 class namespace_name::ExampleController < 应用程序控制器

Modularity

当您将控制器 (类) 放入子目录时,Ruby/Rails 期望它从父目录 (module) subclass:

#app/controllers/group_a/a_thing_controller.rb
class GroupA::AThingController < ApplicationController
  def index
  end
end

#config/routes.rb
get :a_thing, to: "group_a/a_thing#index" #-> url.com/a_thing

我已经更改了您的模型/目录名称以符合 Ruby snake_case convention:

  • Use snake_case for naming directories, e.g. lib/hello_world/hello_world.rb
  • Use CamelCase for classes and modules, e.g class GroupA

Rails路由有namespace directive帮助:

#config/routes.rb
namespace :group_a do
  resources :a_thing, only: :index #-> url.com/group_a/a_thing
end

... 还有 module 指令:

#config/routes.rb
resources :a_thing, only: :index, module: :group_a #-> url.com/a_thing
scope module: :group_a do
  resources :a_thing, only: :index #->  url.com/a_thing
end

区别在于namespace在你的路由中创建了一个子目录module只是将路径发送到子目录控制器。

以上两者都需要子目录控制器上的 GroupA:: 超类。