0

I am getting this error, don't know why.

NameError (uninitialized constant ShopsController::ShopService

My controller name is ShopsController I've made a service /app/services/shop_service.rb The name of the class inside the service is ShopService I'm using it inside a controller action the following way:

flag = ShopService.new.save_categories(@shop, params[:category])

The service code is written below

class ShopService  
  def initialize(shop = nil, services = nil); end
  def save_categories(shop, services)
    debugger
    flag = true
    services.drop(1).each do |service|
      category = Category.new(service: service, shop_id: shop.id)
      flag = false unless category.save
    end
    flag
  end
end
Muhammad Zubair
  • 466
  • 5
  • 17
  • As the error points out `ShopService` is not defined inside the `ShopsController` namespace. Maybe just calling `ShopService` with the global namespace solves the issue. Try changeing `ShopService.new` to `::ShopService.new` – R. Sierra Jul 14 '21 at 18:11

1 Answers1

1

Try to call the service like that: flag = ::ShopService.new.save_categories(@shop, params[:category]) on the controller, this should work

Edit:

Also, check that you are loading the services path in the config/application.rb, on the config.autoload_paths

Muhammad Zubair
  • 466
  • 5
  • 17
  • `NameError (uninitialized constant ShopService):` Got this error now – Muhammad Zubair Jul 14 '21 at 19:19
  • 1
    Humm can you double check the file name and the class name. See to if you loading the `services` path on the `config/application.rb`, on the `config.autoload_paths` – Allan Siqueira Jul 14 '21 at 19:48
  • Yes, that was the issue exactly. Thanks. I used the following link to add services to `autoload_paths` https://stackoverflow.com/questions/32873343/why-doesnt-rails-autoload-classes-from-app-services – Muhammad Zubair Jul 14 '21 at 20:18