通过闪存传递错误消息 [英] Passing error messages through flash
问题描述
在重定向时推送错误消息的最佳方式是什么?
What is the best way to push error messages on redirect to?
我之前使用过几种方法,但都存在问题.
I've previously used couple of approaches, but both of them has issue.
(1) 在 flash 上传递有错误的整个对象并使用 error_messages_for:
(1) Passing the entire object with error on flash and using error_messages_for:
def destroy
if @item.destroy
flash[:error_item] = @item
end
redirect_to some_other_controller_path
end
我发现这个方法会导致cookie溢出.
I found that this method causes cookie overflows.
(2) 传递单个错误信息:
(2) Passing a single error message:
def destroy
if @item.destroy
flash[:error] = @item.full_messages[0]
end
redirect_to some_other_controller_path
end
这样我只发送一个错误信息,如果有很多怎么办?有人知道更好的方法吗?
This way I only send a single error message, what if there are many? Does Anyone knows a better way?
推荐答案
首先,你可以通过设置一个句子来实现你想要做的事情.
Firstly, you can achieve what you're trying to do by setting a single sentence.
flash[:error] = @item.errors.full_messages.to_sentence
我认为您也可以将其设置为数组而不会溢出 cookie.
I think you could also set it as the array without overflowing the cookie.
flash[:error] = @item.errors.full_messages
但正如其他人所说,Flash 通常最好用于返回特定消息.
But as the other guys say, flash is generally better off being used to return specific messages.
例如
flash[:error] = "We were unable to destroy the Item"
一个常见的模式就是这样.
A common pattern is as such.
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
也就是说,我们有两条路径.
Namely, we have two paths.
- 操作成功.我们重定向.
- 操作失败.我们显示一个页面,显示一个错误,并有
@record.errors
随时调用error_messages_for(@record)
如果我们愿意.
- Action succeeds. We redirect.
- Action fails. We show a page, flash an error, and have
@record.errors
on hand to callerror_messages_for(@record)
if we so wish.
这篇关于通过闪存传递错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!