Rails namespacing error?

2019-07-04 04:26发布

问题:

I have this in my config/routed.db:

namespace :admin do
  resources :users
  resources :events
end

I generated the User model by using the scaffolding Rails provides, then I simply generated a admin/admin controller by using Rails' generate and simply moved all the user-related stuff into the admin sub-directories inside the controllers/views/helpers. Yes, I did have to add admin_ in a few places and inside the form partial I had to change the form_for(@user) to form_for([:admin, @user]).

When I try to create a new user (this is when I POST the user data) I get the following error message:

undefined method `user_url' for #<Admin::UsersController:0x13f408e0>

The application-level trace shows that the error is raised here:

app/controllers/admin/users_controller.rb:47:in `create'

The line of code where this error is raised:

format.html { redirect_to @user, :notice => 'User was successfully created.' }

The above line is inside the respond_to block.

So, I have two questions:

  1. How do I fix this issue?
  2. Is there a smarter, better, rails-way of doing this?

Also, bonus points if you suggest I re-do this in the smarter, better, rails-way! Well, I will do that anyway! :D


Update

Oh, I almost forgot something that might be relevant! I also made Admin::UsersController inherit from Admin::AdminController (which normally in turn inherits from ApplicationController):

Admin::UsersController < Admin::AdminController

回答1:

You need to use the namespace in your redirect, too:

redirect_to [:admin, @user] #...

or

redirect_to admin_user_path(@user) #...