Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating new Model entry using json (Rails)

In my rails application I am trying to create a new user from a json client. However, I am a little stuck on what to send as the json body. The request is properly getting sent to the correct controller, however I keep getting my validations error back as a response. It says the email and username cant be blank. Am I doing someting wrong?

I am POSTing to this url localhost:3000/users.json

I am trying to send this as the json request:

{
 "user":
  {
   "email": "[email protected]",
   "username": "noob1",
  }
}

In my create action i have this:

 # POST /users
  # POST /users.json
  def create
    @user = User.new(params[:user])

    respond_to do |format|
      if @user.save
        format.html { redirect_to @user, notice: 'User was successfully created.' }
        format.json { render json: @user, status: :created, location: @user }
      else
        format.html { render action: "new" }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

Here are my routes:

users GET    /users(.:format)          users#index
          POST   /users(.:format)          users#create
 new_user GET    /users/new(.:format)      users#new
edit_user GET    /users/:id/edit(.:format) users#edit
     user GET    /users/:id(.:format)      users#show
          PUT    /users/:id(.:format)      users#update
          DELETE /users/:id(.:format)      users#destroy
like image 541
thunderousNinja Avatar asked Dec 29 '25 04:12

thunderousNinja


1 Answers

What are you using to send the POST? make sure that you have the Content-Type header set to application/json.

Also, try POSTing to localhost:3000/users.json.

like image 58
cjhveal Avatar answered Dec 30 '25 19:12

cjhveal