1

我有一个类,我正在使用 validates 方法来检查长度,并且我想将实际长度注入错误消息中。这可能吗?

这是我当前使用验证的课程:

class Something
  validates :summary, :detail, :length => { 
    :in => 300..500,
    :too_short => "must have at least %{count} letters",
    :too_long => "must have at most %{count} letters"
  }

错误信息显示:

2 errors prohibited this job from being saved.

Summary must have at least 300 letters
Detail must have at least 300 letters

但我想展示:

...
Summary is only 250 letters and must have at least 300 letters
...
4

2 回答 2

1

对于您的解决方案,您可以通过自定义验证

validate:summary_length

def summary_length 
  if self.summary.length < 10 && !self.summary.blank?
    errors[:base] << "is only #{self.summary.size} letters and must have at least 10 letters"
  end
end
于 2012-11-08T06:16:25.570 回答
0

试试这个,似乎对我有用:

class Something
    validates :summary,    
        :in => 300..500,
        :too_short => "summary is only #{summary.length} and must have at least %{count} letters"
        # etc.
    validates :detail,
        :in => 300..500,
        :too_short => "detail is only #{detail.length} and must have at least %{count} letters
       # etc.
于 2012-11-08T05:33:20.783 回答