在哪里在Rails中对模型验证失败的控制器进行渲染?
我在我的rails应用程序中有一个简单的视频模型, has_many
注释。我在视频的展示页上显示这些评论。当我提交表单一切正常;然而,如果在评论模型上有验证错误,那么我的系统爆炸。如果在注释模型上有验证错误,我只想再次呈现视频的显示页面,验证错误样式显示。我如何在我的创建动作内这样做?非常感谢!
I have a simple Video model in my rails app that has_many
comments. I am displaying these comments on the video's show page. When I submit the form everything works fine; however, if there are validation errors on the Comment model, then my system blows up. If there are validation errors on the Comment model, I would simply like to render the video's show page again, with the validation error styling showing. How do I do this inside of my create action? Thanks a lot!
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
为此,你必须渲染一个模板:
To do this you'll have to render a template:
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 :template => 'videos/show'
end
end
end
Keep记住,你必须在CommentsController#create操作中声明任何实例变量(如@video),因为VideosController#show操作不会运行,模板将被简单地渲染。例如,如果您在VideosController#show操作中有一个@video_name变量,则必须向CommentsController#create操作添加相同的@video_name实例变量。
Keep in mind that you'll have to declare any instance variables (like @video) inside of the CommentsController#create action as well though, because the VideosController#show action will not be run, the template will simply be rendered. For instance, if you have an @video_name variable in your VideosController#show action, you'll have to add the same @video_name instance variable to the CommentsController#create action.