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)
也就是说,我们有两条路.
@record.errors
随时打电话error_messages_for(@record)
.