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
Try to change location: @user
to location: v1_user_url(@user)
Try reversing your namespace and scope:
namespace :api, path: '/' do
scope module: :v1 do
resources :users
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With