2014-09-05 15 views
0

我正在使用rails4。在我的控制器中,我解析了json並存入數據庫。 我的控制器是這樣的,使用create處理錯誤!方法在Rails4中

def store 
    @data.each do |invite| 
    MemberInvitation.create!(:email => invite['email']) 
    end 
end 

這工作得很好....

我們知道create will automatically call validators但如果驗證失敗如何使用JSON渲染顯示錯誤消息。因爲我在MemberInvitation模型中定義驗證。

如何處理這種情況!

我想呈現JSON格式的錯誤消息,如果錯誤提出!

回答

2

一個快速的方法來得到一個報告:

def store 
    errors = [] 
    @data.each do |invite| 
    new_member = MemberInvitation.new(:email => invite['email']) 
    errors.push(new_member) unless new_member.save 
    end 
    if errors.empty? 
    #everything went fine 
    else 
    # you have all members with issues in the array 
    # I advise you to create your json yourself 
    end 
end 
+0

柏迪創建存儲在數據庫中的最後一封電子郵件,而無須給予任何錯誤信息!它應該顯示錯誤信息而不是存儲到數據庫中! – RubyOnRails 2014-09-05 07:39:45

+0

保持冷靜。有什麼問題?如果有一個單一的錯誤,你不希望任何成員持續存在? – apneadiving 2014-09-05 07:41:05

+0

@RubyOnRails新將只啓動一個對象,沒有什麼是保存到分貝尚未在該行 – Nimir 2014-09-05 07:43:24