Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 5 api - undefined method `user_url'

I started a new project with Rails 5 in API mode.

For the moment i just create the project, set the database and use the scaffold command.

rails g scaffold User

I try my code with postman to create a new user (POST)

Request

URI localhost:3000/v1/users
{
    "first_name": "Firstname",
    "last_name": "Lastname",
    "email": "[email protected]"
}

Result

#<NoMethodError: undefined method `user_url' for #<Api::V1::UsersController:0x005594d8a4ad90>

How can i fix that error ?

routes.rb

Rails.application.routes.draw do
  scope module: 'api' do
    namespace :v1 do
      resources :users, :as => 'user'
    end
  end
end

users_controller.rb

# POST /users
def create
  @user = User.new(user_params)

  if @user.save
    render json: @user, status: :created, location: @user
  else
    render json: @user.errors, status: :unprocessable_entity
  end
end
like image 807
Sancho Avatar asked Dec 04 '16 10:12

Sancho


2 Answers

Try to change location: @user to location: v1_user_url(@user)

like image 176
Raúl Cabrera Avatar answered Nov 09 '22 14:11

Raúl Cabrera


Try reversing your namespace and scope:

namespace :api, path: '/'  do
  scope module: :v1 do
    resources :users
  end
end
like image 1
mrlindsey Avatar answered Nov 09 '22 12:11

mrlindsey