由于销毁操作重定向到索引操作,如何在销毁操作上显示错误消息?
在我的模型中:
before_destroy :ensure_not_referenced_by_any_shopping_cart_item
并且
def ensure_not_referenced_by_any_shopping_cart_item
unless shopping_cart_items.empty?
errors.add(:base, "This item can't be deleted because it is present in a shopping cart")
false
end
end
当该商品出现在购物车中时,它不会被销毁(这很好),并且如果我将其记录在操作中,我会看到错误..
def destroy
@product = Beverage.find(params[:id])
@product.destroy
logger.debug "--- error: #{@product.errors.inspect}"
respond_to do |format|
format.html { redirect_to beverages_url }
format.json { head :ok }
end
end
..但是错误所在的实例变量当 redirect_to
发生时,设置的消息将被放弃,因此用户永远不会看到它。
应如何将错误消息保留到下一个操作,以便可以在其视图中显示?
谢谢!
In a model I have:
before_destroy :ensure_not_referenced_by_any_shopping_cart_item
and
def ensure_not_referenced_by_any_shopping_cart_item
unless shopping_cart_items.empty?
errors.add(:base, "This item can't be deleted because it is present in a shopping cart")
false
end
end
When the item is present in a cart, it is not destroyed (which is good), and I see the error if I log it in the action..
def destroy
@product = Beverage.find(params[:id])
@product.destroy
logger.debug "--- error: #{@product.errors.inspect}"
respond_to do |format|
format.html { redirect_to beverages_url }
format.json { head :ok }
end
end
..but the instance variable on which the error message was set is abandoned when the redirect_to
happens, so the user never sees it.
How should the error message be persisted to the next action so it can be shown in its view?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我建议使用闪存消息来转发错误信息。
有这样的效果。这就是我在自己的应用程序中处理类似问题的方式,但这取决于您想要向用户显示的信息的详细信息。
I would recommend using a flash message to relay the error information.
Something to that effect. That is how I have handled similar issues in my own apps, but it depends on the detail of information you want to display to the user.
您需要将错误放入闪存中。大致类似于
请注意,您还需要在
application.html.erb
文件中打印消息。You need to put the error in the flash. Something roughly like
Note that you also need to be printing out messages in your
application.html.erb
file.您可以使用两条消息来完成此操作,一条消息的状态为 OK,另一条消息的状态为 NO OK(unprocessable_entity,例如 这里还有更多)。
You can do it with two messages, one with the status OK, and another with NO OK (unprocessable_entity for example, here's more).
在 Rails 4 中,你可以这样做
In Rails 4, you can do like that