2011-04-03 71 views
2

我正在编写我的第一个自定义rails验证,并且如果它们返回false,我想用html“error”类标记违规类 - 我无法弄清楚如何做到这一点。下面的相关验证代码 - 任何帮助表示赞赏。Rails 3自定义验证:突出显示违规字段

(如果它的确与众不同,我使用jQuery)

validates_each :shop do |record, attr, value| 
    shopvar = record.shops.map{ |s| s.email.downcase.strip } 

    if shopvar.count != shopvar.uniq.count 
     record.errors.add(attr, 'has the same email address entered more than once') 
     #record.errors[attr] << "You have entered this shop in the form twice" 
    end 
    end 

回答

3

因此,在您的形式你有这样的事情输入域

<%= form.text_field :title %> 

由于错误是哈希你可以使用“包括?”像这样的方法...

errors.include?(:title) 

这告诉你这个字段有问题。现在你需要做的就是设计风格。

捶在三元运营商ASI ...

<% css_class = errors.include?(:title) ? "highlight_error_class" : "no_problem_class" %> 
<%= form.text_field :title, :class => css_class %> 

完成。