Rails Routing Namespaces with Nested Routes can cause Model failures.
Working on my side project, I refactored some controllers into an admin namespace, resulting in a directory tree that looked something like this:
-controllers/
-admin/
-item/
-photo_controller.rb
-item_controller.rb
All the tests passed, yet whenever I hit my (previously working) admin/items controller, I got:
NoMethodError (undefined method `find' for Admin::Item:Module): app/controllers/admin/items_controller.rb:7:in `index'
It looked like the route was somehow forcing the namespacing of the model. I went nuts googling for it and found zero explanations. Finally, on a hunch, I renamed the item directory to items and the photo_controller to Admin::Items::PhotoController instead of Admin::Item::PhotoController and everything worked.
Another option is to use ::Item in your controller instead of Item. I think I might go with this one — would rather be more specific than resort to naming tricks.
I’m still bewildered as to how or why this is happening — I can’t quite see how having an Admin::Item:: namespace means that all of the sudden, Item will now refer to Admin::Item, although I do have a pet theory. Perhaps when Item is not found in the current namespace, it goes UP a namespace and eventually hits the model. Since I now have an Admin::Item, it doesn’t bother looking in the main namespace.
I can’t believe this was so tough to google for. I imagine this would nail anyone who has a nested route in a namespace. I’m a bit surprised it’s not a more common error.
I’m assuming tests didn’t fail because the Admin::Item::PhotosController was not loaded during the Admin::ItemsController test.