简体   繁体   中英

Empty params on POST request to a Rails 4 API

I just started coding in Rails in order to create an API an I've already hit a wall. I'm trying to create a user using a POST request. Here's my users controller which was created using the scaffold command:

def create
@user = User.new(params[:user])

logger.info(@user.to_json)

if @user.save
 render json: @user, status: :created, location: @user

else
  render json: @user.errors, status: :unprocessable_entity
end

end

The user model only has one validation validates :name, presence: true and that keeps failing because apparently the params is always empty. To test the calls I'm using Postman - REST Client on Chrome and the URL I'm hitting is http://localhost:3000/users . I'm not sure what is it that I'm doing terribly wrong. The same setup with the form and http works fine.

I tried formatting the JSON object in different ways but nothing works. So far I've used:

  1. {"user":{"name":"test"}}
  2. {{"name":"test"}}

It's because it's not allowing it through. Rails 4 introduced strong parameters

You can use an adjacent method, and call that.

def create
  @user = User.new(user_params)

  logger.info(@user.to_json)

  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(:field1, :field2)
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM