简体   繁体   English

Rails新手:关于控制器中错误处理的建议

[英]Rails Newbie: Recommendations for error handling in controller

Sorry if the question is obvious, I am only starting to work with Rails. 抱歉,如果问题很明显,我才开始使用Rails。
I have a following code in several controller methods now: 我现在在几种控制器方法中有以下代码:

respond_to do |format|
    if @project.save
        format.html { redirect_to(edit_project_url(@project), :notice => '#{user.name} added to #{role}.') }
        format.js
    else
        format.html { render :action => "edit" }
        format.js #...
    end
end

So the question is, what is the best way to do the same thing for errors in all methods? 所以问题是,对所有方法中的错误进行相同操作的最佳方法是什么?
Is it recommended that I use save! 建议我使用save! and handle it in rescue_action ? 并在rescue_action处理它?

Or should I do my own respond method and pass save in a block? 还是我应该做自己的respond方法并通过块save

It's often more convenient to use the exception-raising variant of save and rescue that later in the block than to branch like that. 通常,在块中的较晚位置使用保存和抢救的引发异常的变体,比那样分支更方便。 The advantage to exceptions is they'll bust out of transactions. 例外的好处是它们会退出交易。

def create
  @project.save!

  respond_to do |format|
    format.html { redirect_to(edit_project_url(@project), :notice => '#{user.name} added to #{role}.') }
    format.js
  end

rescue ActiveRecord::RecordInvalid
  respond_to do |format|
    format.html { render :action => "edit" }
    format.js #...
  end
end

You'll find that it gets really tricky to wrangle your way out of a pile of nested if statements when trying to save more than one object at a time, but a simple rescue for exceptions will handle it neatly. 您会发现,一次尝试保存多个对象时,从一堆嵌套的if语句中纠缠出自己的方式确实很棘手,但是对异常的简单rescue将巧妙地处理它。

def create
  Project.transaction do
    @project.save!
    @something_else.save!
    @other_stuff.save!
  end

  # ...
rescue ActiveRecord::RecordInvalid
  # ...
end

If any one of those saves blows up you'll get an exception. 如果其中任何一项保存被炸毁,您将获得一个例外。 To ensure that all of them are displaying validation errors you might have to call .valid? 为了确保所有这些都显示验证错误,您可能必须调用.valid? on each to prime them or you will have those after the failure left untested. 在每一个上进行灌注,否则在未经测试的情况下就会得到它们。

It's not a bad thing to use the if @object.save pattern. 使用if @object.save模式不是一件坏事。 However, if you are doing exactly the same for all your actions on your controller, you can define a rescue_from action. 但是,如果您对控制器上的所有操作都执行完全相同的操作,则可以定义一次rescue_from操作。

Something like 就像是

class MyController < ActionController::Base
  rescue_from ActiveRecord::RecordInvalid do
    render :action => edit
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM