I'm fairly new to Ruby but I have read dozens of articles and ended up with no solution for this issue:
I'm trying to make my API controller bulletproof. In order to validate requests, I'm using ActionController::Parameters .
For example, in my Users
API controller:
params.require(:user).permit(:email)
If someone calls this with {"user": "abc"}
, it results in an error, and HTTP 500, when it's clearly the user's fault for not passing in user
as a hash, and should result in a HTTP 400:
NoMethodError in API::UsersController#update
undefined method `permit' for "abc":String Did you mean? print
How do I ensure the user of my API passes in a hash?
There is this method that you can use: dig (ruby 2.3):
Retrieves the value object corresponding to the each key objects repeatedly.
http://ruby-doc.org/core-2.3.0_preview1/Hash.html#method-i-dig
So you could say params.dig(:user, :email)
You could also say params[:user].has_key?(:email) but the first one is better
Also on related note not sure if you should handle with 400 - I think that 422 may be better since it is 422 - Unprocessable Entity
but not important...
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.