Barbared
Barbared

Reputation: 800

Rails: weird behaviour in form_for

I have a namespaced resource but just in controller directories. So in routes.rb:

namespace :admin do
  resources :user
end

which means this:

admin_user_index GET    /admin/user(.:format)                  admin/user#index
                 POST   /admin/user(.:format)                  admin/user#create
  new_admin_user GET    /admin/user/new(.:format)              admin/user#new
 edit_admin_user GET    /admin/user/:id/edit(.:format)         admin/user#edit
      admin_user GET    /admin/user/:id(.:format)              admin/user#show
                 PUT    /admin/user/:id(.:format)              admin/user#update
                 DELETE /admin/user/:id(.:format)              admin/user#destroy

Everything works fine except the action "new" and this is weird since the _form render is the same in the "edit" action and that works fine. This is my controller within admin directory:

class Admin::UserController < ApplicationController
# GET /users
def index
  @users = User.all
end

# GET /users/1
def show
  @user = User.find(params[:id])
end

# GET /users/new
def new
  @user = User.new
end

# GET /users/1/edit
def edit
  @user = User.find(params[:id])
end

# POST /users
def create
  @user = User.new(params[:user])
  respond_to do |format|
    if @user.save
      format.html { redirect_to @user, notice: 'User was successfully created.' }
    else
      format.html { render action: "new" }
    end
  end
end

# PUT /users/1
def update
  @user = User.find(params[:id])
  respond_to do |format|
    if @user.update_attributes(params[:user])
      format.html { redirect_to [:admin ,@user], notice: 'User was successfully updated.' }
    else
      format.html { render action: "edit" }
    end
  end
end

end

And this is the first line of the form which cause the error: undefined method `admin_users_path'

<%= form_for [:admin, @user] do |f| %>

I can't figure out where the error is. Any advise?

Upvotes: 0

Views: 173

Answers (1)

Peter Brown
Peter Brown

Reputation: 51717

Rails conventions say that controllers should be pluralized. If you don't want to follow that convention, you can set the URL in the form_for tag with :url => admin_user_path(@user). I highly recommend using the Rails conventions though, otherwise you'll constantly be battling with issues like this where you need to override the defaults.

You can easily update this code to use the Rails conventions by changing your controller class to Admin::UsersController and the route to resources :users

Upvotes: 2

Related Questions