【问题标题】:Ruby on Rails - Controller SubdirectoryRuby on Rails - 控制器子目录
【发布时间】:2016-05-20 06:33:58
【问题描述】:

我对 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/ 上收到以下错误:

AthingController 类的超类不匹配

比如:

class AthingController < ApplicationController
  def index
  end
end

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

【问题讨论】:

    标签: ruby-on-rails ruby controller routes subdirectory


    【解决方案1】:

    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:

    • 使用snake_case 命名目录,例如lib/hello_world/hello_world.rb
    • 对类和模块使用CamelCase,例如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:: 超类。

    【讨论】:

      【解决方案2】:

      在 config/routes.rb 中

      namespace :namespace_name do
        resources : resource_name
      end
      

      在应用程序/控制器/

      用你的命名空间名称创建一个模块名称,在那个地方你的控制器 在那个控制器类名应该像 类命名空间名称::ExampleController

      【讨论】:

        【解决方案3】:

        尝试改用命名空间:

        在您的路线中:

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

        在您的控制器中:

        class Groupa::AthingController < ApplicationController
        

        在浏览器中:

        localhost:3000/groupa/athing/
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-04-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多