模型验证失败时,在哪里在 Rails 中呈现评论控制器? [英] Where to render comments controller in Rails on model validations failure?

查看:23
本文介绍了模型验证失败时,在哪里在 Rails 中呈现评论控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 rails 应用中有一个简单的视频模型,has_many 注释.我正在视频的显示页面上显示这些评论.当我提交表单时,一切正常;但是,如果 Comment 模型上存在验证错误,那么我的系统就会崩溃.如果 Comment 模型上存在验证错误,我只想再次呈现视频的显示页面,并显示验证错误样式.我如何在我的创建操作中执行此操作?非常感谢!

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

请记住,您还必须在 CommentsController#create 操作中声明任何实例变量(如 @video),因为 VideosController#show 操作不会运行,模板将简单地呈现.例如,如果您的 VideosController#show 操作中有一个 @video_name 变量,则必须将相同的 @video_name 实例变量添加到 CommentsController#create 操作中.

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.

这篇关于模型验证失败时,在哪里在 Rails 中呈现评论控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆