在重定向上推送错误消息的最佳方法是什么?
我之前使用过几种方法,但两者都存在问题.
(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)
这种方式我只发送一条错误信息,如果有很多怎么办?有谁知道更好的方式?
我想像这样使用渲染:
render :action => 'page#form'
Run Code Online (Sandbox Code Playgroud)
我也试过这个:
render :template => 'site/page#form'
Run Code Online (Sandbox Code Playgroud)
那也行不通.此特定页面上的表单位于最底层,如果在提交时出现任何错误,我会讨厌将用户默认为页面顶部.我还需要使用render(而不是重定向),因为我需要保留对象及其错误.
如何渲染以定位特定锚标记?
我在我的rails应用程序中有一个简单的视频模型has_many评论.我在视频的节目页面上显示这些评论.当我提交表格时,一切正常; 但是,如果评论模型上存在验证错误,那么我的系统就会爆炸.如果评论模型上存在验证错误,我只想再次渲染视频的显示页面,并显示验证错误样式.如何在我的创建操作中执行此操作?非常感谢!
class CommentsController < ApplicationController
def create
@video = Video.find(params[:video_id])
@comment = @video.comments.build(params[:comment])
if @comment.save
redirect_to @video, :notice => 'Thanks for posting your comments.'
else
render # what? What do I render in order to show the video page's show action with the validation error styling showing? Please help!
end
end
end
Run Code Online (Sandbox Code Playgroud)