2013-07-11 22 views
0

我很好奇控制器的行为,我如何才能做一些嵌套参数的简单验证?构建一个有条件检查嵌套参数的ruby

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? 

这种类型的支票是barfing。我试图扫描一些嵌套的JSON参数,可以使例如,使上

"person": 
      { 
        "email":"[email protected]", 
        "name":"foo" 
      }, 

POST请求这将验证很好,因为嵌套的名字是存在的。虽然如果我没有嵌套值的请求,它会barf。我怎么能写一个条件来检查嵌套的值,只有在错误值为空的情况下才会填充。否则,如果不存在嵌套值,则照常继续。

回答

1

你可以使用has_key?方法可用于Hash类。

errors << "person email should not be empty" if person.has_key?(:email) && person[:email].blank? 
+0

作品完美!谢谢。 – stonep