簡體   English   中英

Rails中的事務回滾錯誤對象

[英]Transaction rollback Error object in Rails

我想顯示在交易過程中收到的錯誤消息。 這是我的student.rb(模型)

def self.createStudent (user , student , father , mother)
    begin
      transaction do
        father.save!
        mother.save!
        user.save!
        student.mother=mother
        student.father=father
        student.user=user
        student.save
      end
    rescue ActiveRecord::RecordInvalid => invalid
      return 
    end
  end

然后從控制器調用此方法

Student.createStudent(@user,@student,@father,@mother)

現在我想再次檢查控制器,保存后是否有任何錯誤。 並發回查看

無論成功還是失敗,都可以從此方法返回值。

def self.createStudent (user , student , father , mother)
  begin
    transaction do
      father.save!
      mother.save!
      user.save!
      student.mother=mother
      student.father=father
      student.user=user
      student.save
    end 
    return "success"
  rescue ActiveRecord::RecordInvalid => invalid
    return invalid.record.errors
  end
end

現在,您可以在控制器中檢查返回值,並根據返回值在視圖中顯示消息。

編輯 (根據您的評論):

invalid.record.errors將具有事務失敗的錯誤。

檢查文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM