Vladimir Fomin
Vladimir Fomin

Reputation: 343

Adding namespace in Rails and routing error

I tried to add namespace in my RoR project.

It works as expected:

controller:

class Dashboard::CategoriesController < ApplicationController
...some code
end

routes.rb

namespace "dashboard" do
  resources :categories
end

but it doens'y work:

class Dashboard::UsersController < ApplicationController
 ...some code
end

class Dashboard::CardsController < ApplicationController
 ...some code
end

routes.rb:

namespace "dashboard" do
  resources :users do
    resources :cards do
      member do
        post 'review'
      end
    end
   end
 end

it throws an routing error: uninitialized constant CardsController

what's wrong?

Upvotes: 1

Views: 116

Answers (2)

Richard Peck
Richard Peck

Reputation: 76774

First of all, you'll be better making your routes more compacted:

#config/routes.rb
namespace :dashboard do
   resources :users do
      resources :cards do
          post :review #-> domain.com/dashboard/users/:user_id/cards/1
      end
   end
end

The error it self will likely be caused by the way in which you're trying to call the controller. Typically, you'll receive errors with the namespace prepended to the class name (Dashboard::CardsController). In this instance, it just says CardsController.

You'll need to look at how you're calling the route.

Specifically, I presume you're using a form_for - which will build the route for you. If this is the case, you'll need to use the namespace within the form_for declaration itself:

<%= form_for [:dashboard, @user, @card], url: dashboard_user_cards_review(@user, @card) do |f| %>

Upvotes: 1

Lucas
Lucas

Reputation: 2637

Rails auto loads class if its name match file name. Error indicates that CardsController class is not loaded, so most probably you named your controller file wrongly. It should be app/controllers/dashboard/cards_controller.rb.

Upvotes: 2

Related Questions