2013-07-11 21 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