I'm making a Rails app, and I'd like a controller to gracefully handle an improperly formatted request. So, ideally, the parameters hash would look like this:
{"user" => { "username"=>"user1212" } }
But if someone sends data that looks like this:
{"user" => "user1212" }
I want to be able to raise a descriptive error, preferably a ParameterMissing. Right now, my user_params method looks like this:
def user_params
params.require(:user).require(:username)
end
But if params.require(:user)
returns a string, as in the second example, I get a NoMethodError. I tried params[:owner].require(:username)
but that gives a TypeError. I've tried a bunch of combinations of permit and require, but I haven't found a solution I like. Is there a nice, clean way to require that params[:user] be a hash?
params.require(:user).permit(:username)
? – Pavan