0

我可以在 Rails 中拥有 3 级深度继承的控制器吗?有人会认为这样一件微不足道的事情是可能的,但是“第三”级的具体控制器给出了“未初始化常量 Ns2::SecondController”的通用/无用错误

这基本上是这段代码(我没有尝试过这个确切的代码)

module Ns3
  class ThirdController < Ns2::SecondController
  end
end

module Ns2
  class SecondController< Ns1::FirstController
  end
end

module Ns1
  class FirstController< ApplicationController
  end
end

注意:在路由和所有此类目录中使用命名空间应正确设置。

我确信我可以重新安排逻辑并使用 mixins 或 helpers 获得一些东西。但是,为了我自己的利益,我希望立即回答这个问题。是/否或方式通过了错误。对重构变通解决方案 ATM 不感兴趣。虽然我猜它不会受伤。

谢谢

4

2 回答 2

0

它很可能是类名或文件名中的拼写错误。

您需要将类放在正确的文件/目录结构中,以便 Rails 自动加载工作,例如:

#/controllers/ns3/third_controller.rb
module Ns3
  class ThirdController < Ns2::SecondController
  end
end

#/controllers/ns2/second_controller.rb
module Ns2
  class SecondController < Ns1::FirstController
  end
end

#/controllers/ns1/first_controller.rb
module Ns1
  class FirstController < ApplicationController
  end
end

另一件要尝试的事情是从根命名空间开始使用::前缀,如下所示:

module Ns1
  class SecondController < ::Ns1::FirstController
  end
end

你也可以试试这个:

#/controllers/ns3/third_controller.rb
class Ns3::ThirdController < ::Ns2::SecondController
end
于 2013-05-15T16:42:57.707 回答
0

这是可以做到的。

然而,看起来 RoR 很奇怪,你必须为基类隐式指定命名空间。如果你让它默认为当前命名空间,它的行为会很奇怪。

于 2013-05-15T15:58:15.317 回答