通过闪存传递错误消息

ale*_*333 29 ruby ruby-on-rails

在重定向上推送错误消息的最佳方法是什么?

我之前使用过几种方法,但两者都存在问题.

(1)在flash上​​传递整个对象并使用error_messages_for:

  def destroy
    if @item.destroy
      flash[:error_item] = @item
    end
    redirect_to some_other_controller_path
  end
Run Code Online (Sandbox Code Playgroud)

我发现这种方法导致cookie溢出.

(2)传递单个错误消息:

  def destroy
    if @item.destroy
      flash[:error] = @item.full_messages[0]
    end
    redirect_to some_other_controller_path
  end
Run Code Online (Sandbox Code Playgroud)

这种方式我只发送一条错误信息,如果有很多怎么办?有谁知道更好的方式?

Mat*_*udy 70

首先,你可以通过设置一个句子来实现你想要做的事情.

flash[:error] = @item.errors.full_messages.to_sentence
Run Code Online (Sandbox Code Playgroud)

我认为您也可以将其设置为数组而不会溢出cookie.

flash[:error] = @item.errors.full_messages
Run Code Online (Sandbox Code Playgroud)

但正如其他人所说,闪存通常更适合用于返回特定消息.

例如.

flash[:error] = "We were unable to destroy the Item"
Run Code Online (Sandbox Code Playgroud)

一种常见的模式就是这样.

def some_action
  if @record.action
    flash[:notice] = "Action performed successfully"
    redirect_to @record      
  else
    flash[:error] = "Action failed"
    render :action => "some_action"
  end
end
Run Code Online (Sandbox Code Playgroud)

也就是说,我们有两条路.

  1. 行动成功.我们重定向.
  2. 行动失败.如果我们愿意的话,我们会显示一个页面,闪现错误,并@record.errors随时打电话error_messages_for(@record).

  • 对于你的例子的'else'部分,你应该使用`flash.now [:error] ="动作失败"`参见:[the-flash](http://guides.rubyonrails.org/action_controller_overview.html#the-闪) (3认同)