【问题标题】:Where to render comments controller in Rails on model validations failure?在模型验证失败时在哪里渲染 Rails 中的注释控制器?
【发布时间】:2011-07-07 17:14:31
【问题描述】:

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

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

【问题讨论】:

    标签: ruby-on-rails controller render


    【解决方案1】:

    为此,您必须渲染一个模板:

    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 动作中。

    【讨论】:

      【解决方案2】:

      我也有同样的问题。我认为您的问题与Rails validation over redirect 重复(最近custom validations errors form controller inside other parent controller rails 3.1 也重复)。

      Pan Thomakos 上述解决方案的问题在于,如果 VideosController#show 中包含大量代码,那么您将无法在不违反 DRY 规则的情况下从 videos/show 模板进行渲染。这是related discussion

      This post from Ryan Bates 的 Railscasts 名望建议您可以将 @video 存储在闪存中以将其保留在重定向中;但是,当我尝试这样做时,它作为正确类的实例出现在另一端,但它没有您期望的任何超类 - 最重要的是ActiveRecord::Base。起初我以为他的建议可能已经过时了(写于 2006 年)。然而,在 2009 年 10 月写的对Rails validation over redirect 的答案之一提倡使用相同的方法,尽管通过自定义的clone_with_errors 方法获取模型实例的浅表副本以避免更深的对象出现问题。但即使采用这种方法,任何依赖超类的方法都不起作用。我猜这是对象被序列化到闪存中然后反序列化出来的结果。

      我找到了page written in 2007 which advocates against storing model object instances in the session

      我还找到了good argument in the formtastic google group pointing out that redirecting on validation failure is not the Rails Way,这可能是个坏主意。但是在涉及多个控制器的情况下,这仍然不能提供一个好的解决方案。或许Cells可以用来解决上面提到的DRY问题。

      否则我想唯一的答案就是坚持使用简单的数据,如对象 ID、错误消息字符串等。

      【讨论】:

        猜你喜欢
        • 2015-12-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-13
        • 1970-01-01
        • 2016-05-08
        • 1970-01-01
        • 2012-12-31
        相关资源
        最近更新 更多