Validations performed but fields not surrounded with field_with_errors div on Rails 3.2.0 only in production

試著忘記壹切 提交于 2019-12-13 01:29:07

问题


I have a Publication model with validations on some fields, title for example.

I removed the error messages that I find annoying, and set up a nice CSS for when the input are surrounded in a field_with_error div so the user knows what field did not validate.

The thing is when I deploy to production the validations are still performed (ie. the user is sent back to the form) but the inputs are not surrounded with the error div.

I tried running the app locally in production mode and all I could learn is that it starts happening when I set config.cache_classes to true in my config/environments/production.rb file.

Also when I log @publication.errors in the controller the errors are present.

Any idea ?


回答1:


On a rails 4.0.1 project I added an initializer:

config/initializers/field_with_errors.rb

with these lines

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:


After digging into Rails itself I found that, in actionpack/lib/action_view/helpers/active_model_helper.rb

Base.field_error_proc.call(html_tag, self)

returns the html_tag without wrapping it in the error div.

Going further that shows that, in actionpack/lib/action_view/base.rb,

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

has been reset or just never set.

So as a workaround I found that putting

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

at the top of any controller solves the issue, I imagine because it's interpreted after rails has loaded.

The question now is how is it possible that it hadn't been loaded the first time, whereas everything else in the app is working just fine ?




回答3:


In my case it was happening because of a gem 'casein' Without this gem it was working fine. Also in development it was working, but not in production.

It was ignoring the initializer I set for field_error_proc. This was because it got overwritten by the gem I guess..

For example see: https://github.com/russellquinn/casein/blob/master/app/controllers/casein/casein_controller.rb

In the end, I copied the controller to my project and removed this line:

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

Then the initializer worked fine in production also.



来源:https://stackoverflow.com/questions/11136120/validations-performed-but-fields-not-surrounded-with-field-with-errors-div-on-ra

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!