An Unexpected Battle Between Models and Controllers: Namespaces 1
I was updating one of our client’s applications from Rails 1.0 to 1.1.2 today. Unfortunately, during the first test spin, I got an ‘Uninitialized Constant BaseController’ error on all of my pages within a module. In this app we have a module that groups a bunch of related controllers. All of these controller then inherit from the BaseController in that folder. For example,
- controllers
- one_controller.rb
- fruit
- base_controller.rb
- apple_controller.rb
- etc.
juice_controller.rb
- etc.
All of the controllers in the module were then defined like
class Fruit::AppleController < Fruit::BaseController
Note: this worked in Rails 1.0
I searched and searched. I couldn’t find anything, in the code or online. Finally, I tried creating another module to see if modules were simply broken in the 1.1 version of rails. Nope, the test worked great. So I knew that the problem had to be with this specific module.
Then it hit me. I also had a module with the same name; in this case – fruit.
Models are defined like
class Fruit < ActiveRecord::Base
And this was the problem; there was a namespace conflict between my model class and my controller class. When rails would try to load my apple controller, it would look for a subclass of my fruit model, not my fruit controller class.
Luckily for me, we had stopped using that particular model and it hadn’t been deleted yet. With a quick
script/destroy model Fruit
our app was back up and running correctly.
Is this how this should be behaving? I guess so, though the script/generate could be nicer by warning us that we have a namespace conflict.
Anyone else have similar problems?
I have been looking everywhere for the answer to this. Thank you!
By the way, here’s something especially weird. On my dev box, this problem doesn’t happen; on my clients’ server, it does. He swears he’s on the same version of Rails (1.1.6). I don’t know, it’s weird.