문제

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":"foo@gmail.com",
                    "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.

도움이 되었습니까?

해결책

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?
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top