Rails NameError uninitialized constant (collision between model and namespace)

I have a model called Organization . It is defined in app/models/organization.rb

 class Organization < ActiveRecord::Base ... code end 

I have a controller named Admin::Organization::ActivitiesController . It is defined in app/controllers/admin/organization/activities_controller.rb . It has an index action.

 class Admin::Organization::ActivitiesController < ApplicationController def index @organization = Organization.new ... more code end end 

I get the following message when I perform the specified index action:

 NameError in Admin::Organization::ActivitiesController#index uninitialized constant Admin::Organization::ActivitiesController::Organization 

For some reason, it is looking at an organization model inside a controller class. If I changed the index method to use

 @organization = ::Organization.new 

then it works great.

It appears that this behavior does not appear on the dummy console. If I add the binding.pry call in the index method, then I can call Organization.new or ::Organization.new from the command line, it works fine.

Every other application model works correctly and does not have this strange behavior. I did not write the code initially, so I'm trying to figure out what is going on.

I think this could do something with the namespace in the routes.rb file. There is a namespace that uses the word Organization .

 namespace :admin do namespace :organization resources :activities end end 

As a test, I changed the namespace to :organizations , and I managed to get it working without requiring :: . Is there a way to structure things or configure routing, so we can have a namespace :organization that doesn't interfere with the model named Organization ?

+5
source share
1 answer

If you just want the path to be correct, you don’t need to put the action controller in the admin/organization namespace folder. Another option would be similar to a scope instead of a namespace.

 # app/controllers/activities_controller.rb class ActivitiesController < ApplicationController def index @organization = Organization.new ... more code end end 

Now configure the routes,

 # config/routes.rb scope 'admin/organization', path: 'admin/organization' do resources :activities end 

This will lead to the creation of such routes,

 Prefix Verb URI Pattern Controller#Action activities GET /admin/organization/activities(.:format) activities#index POST /admin/organization/activities(.:format) activities#create ...... 
+1
source

Source: https://habr.com/ru/post/1233553/


All Articles