0

I have a simple (one table) API and want to stop an error message appearing after a successful POST/create.

Background

The create action looks like so

  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

private
    def user_params
      params.require(:user).permit(:name, :email)
    end

When I post new data into the User model, it works (i.e. the data saves to the database)

curl -H "Accept: application/json" -H "Content-type: application/json" -d '{"name": "IIII", "email": "IIIII"}' "http://localhost:3000/users/somekey"

The problem

Although the POST works, I get the following error

Completed 500 Internal Server Error in 61ms (ActiveRecord: 20.2ms)



NoMethodError (undefined method `user_url' for #<UserssController:0x00007f91363ebee8>):

app/controllers/users_controller.rb:22:in `create'

The error occurs because after the POST, rails tries to redirect to users_url, and because my routes are a little different (i.e. they contain :key, like so: post 'users/:key' => 'users#create'), the users_url route fails.

My question

How do I stop rails attempting to redirect after the successful POST/create?

stevec
  • 41,291
  • 27
  • 223
  • 311

1 Answers1

1

Like I said in comment, the problem was the location argument of a render which trigger a redirection.

The solution is to remove location: @user of the render.

colinux
  • 3,989
  • 2
  • 20
  • 19