【问题标题】:Validations performed but fields not surrounded with field_with_errors div on Rails 3.2.0 only in production在 Rails 3.2.0 上执行了验证,但字段没有被 field_with_errors div 包围,仅在生产中
【发布时间】:2012-06-21 10:22:29
【问题描述】:

我有一个发布模型,对某些字段进行验证,例如标题。

我删除了我觉得烦人的错误消息,并设置了一个漂亮的 CSS,以便当输入被包围在 field_with_error div 中时,用户知道哪个字段没有验证。

问题是,当我部署到生产环境时,仍然会执行验证(即用户被发送回表单),但输入没有被错误 div 包围。

我尝试在生产模式下在本地运行该应用程序,但我所知道的是,当我在我的 config/environments/production.rb 文件中将 config.cache_classes 设置为 true 时,它​​开始发生。

此外,当我在控制器中记录 @publication.errors 时,也会出现错误。

有什么想法吗?

【问题讨论】:

  • 鉴于问题从cache_classes 开始,我们需要查看相关类以了解在缓存时哪个部分可能会导致问题。因此,我将首先发布您的发布模型和控制器。

标签: ruby-on-rails ruby-on-rails-3 validation production-environment


【解决方案1】:

在 Rails 4.0.1 项目中,我添加了一个初始化程序:

config/initializers/field_with_errors.rb

这些行

ActionView::Base.class_eval do
  @@field_error_proc = Proc.new{ |html_tag, instance| "<div class=\"field_with_errors\">#{html_tag}</div>".html_safe }
end

【讨论】:

    【解决方案2】:

    在深入研究 Rails 本身后,我发现在 actionpack/lib/action_view/helpers/active_model_helper.rb 中

    Base.field_error_proc.call(html_tag, self)
    

    返回 html_tag 而不将其包装在错误 div 中。

    进一步表明,在 actionpack/lib/action_view/base.rb 中,

    @@field_error_proc = Proc.new{ |html_tag, instance| "<div class=\"field_with_errors\">#{html_tag}</div>".html_safe }
    

    已重置或从未设置。

    所以作为一种解决方法,我发现把

    ActionView::Base.field_error_proc = Proc.new{ |html_tag, instance| "<div class=\"field_with_errors\">#{html_tag}</div>".html_safe }
    

    在任何控制器的顶部都解决了这个问题,我想是因为它是在 rails 加载后解释的。

    现在的问题是,它怎么可能第一次没有加载,而应用程序中的其他一切都运行良好?

    【讨论】:

    • 感谢ActionView::Base.field_error_proc = Proc.new{ |html_tag, instance| "&lt;div class=\"field_with_errors\"&gt;#{html_tag}&lt;/div&gt;".html_safe }——它帮助了我!
    【解决方案3】:

    就我而言,这是因为宝石“酪蛋白”而发生的 没有这颗宝石,它工作得很好。 它也在开发中,但没有在生产中。

    它忽略了我为 field_error_proc 设置的初始化程序。这是因为它被我猜的 gem 覆盖了..

    例如查看:https://github.com/russellquinn/casein/blob/master/app/controllers/casein/casein_controller.rb

    最后,我将控制器复制到我的项目中并删除了这一行:

    ActionView::Base.field_error_proc = proc { |input, instance| "#{input}".html_safe }
    

    然后初始化程序在生产中也可以正常工作。

    【讨论】:

      猜你喜欢
      • 2011-05-28
      • 1970-01-01
      • 2016-05-20
      • 2011-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-06
      相关资源
      最近更新 更多