0

Can I have controllers in Rails that are 3 levels deep inheritance? One would think such a trivial thing is possible, but the concrete controller at the "third" level gives the generic/useless error of "uninitialized constant Ns2::SecondController"

This is basically with this code (I haven't tried this exact code)

module Ns3
  class ThirdController < Ns2::SecondController
  end
end

module Ns2
  class SecondController< Ns1::FirstController
  end
end

module Ns1
  class FirstController< ApplicationController
  end
end

NOTE: The use of namespaces, within the routes and all such directories should be set up properly.

I'm sure I could rearrange the logic and get something working with mixins or helpers. However, I'd like the immediate question answered for my own benefit. Either Y/N or a way passed the error. Not interested in a refactoring work-around solution ATM. Though I guess it couldn't hurt.

Thanks

Kris
  • 19,188
  • 9
  • 91
  • 111

2 Answers2

0

This can be done.

However it appears RoR is weird, and that you have to implicitly specify the namespace for base classes. If you let it default to the current namespace it acts weird.

0

Its most likely a typo in either the class name or filename.

You need to put the classes in the correct file/directory structure for Rails autoloading to work, e.g:

#/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

Another thing to try is scoping from the root namespace so with a :: prefix, like so:

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

You could also try this:

#/controllers/ns3/third_controller.rb
class Ns3::ThirdController < ::Ns2::SecondController
end
Kris
  • 19,188
  • 9
  • 91
  • 111