Reputation: 309
I'm curious in an controller action, how I can do some simple validation of nested params?
def create
# validate incoming post request
errors = Array.new
person = params[:person]
event = params[:event]
errors << "person email should not be empty" if person[:email].blank?
errors << "person name should not be empty" if person[:name].blank?
errors << "event name should not be empty" if event[:name].blank?
This type of check is barfing. I'm trying to scan for some nested json params, so for example making a post request on
"person":
{
"email":"[email protected]",
"name":"foo"
},
This will validate fine because the nested name is there. Although if I do a request without the nested value, it will barf. How could I write a conditional to check for the nested value, and only stuff in the error value if it's empty. Otherwise, if there is no nested value just continue as normal.
Upvotes: 0
Views: 144
Reputation: 998
You could use the has_key? method available on Hash class.
errors << "person email should not be empty" if person.has_key?(:email) && person[:email].blank?
Upvotes: 1