如何在Rails 3.1中的验证错误失败的字段中显示表单字段突出显示?我知道脚手架会自动生成css和控制器代码来处理这个问题,但我想知道是否有办法手动生成它.我已经通过以下方式实现了错误消息的字符串显示:@ user.errors.full_messages.each …等,但是我无法让字段以红色突出显示.有任何想法吗?
谢谢.
解决方法
假设您的CSS文件中的字段有错误类:
- <% if @user.errors[:name] %>
- <%= f.label :name,:class => "error" %>
- <% else %>
- <%= f.label :name %>
- <% end %>
这是你想要的吗?
额外:here’s a section about customizing default ActiveRecord validations CSS.
编辑:(关于额外的ifs)
- # app/helpers/application_helper.rb
- def field_class(resource,field_name)
- if resource.errors[field_name]
- return "error".html_safe
- else
- return "".html_safe
- end
- end
然后:
- # in your view
- <%= f.label :name,:class => field_class(@user,:name) %>
- <%= f.label :password,:password) %>
- [...]
(我可能在那里犯了一个错误 – 我正在写一个电话 – 但你得到了一般的想法.你可以用多种方式编码这个=无穷大,所以你喜欢这样做…)