我有一个类,我使用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
...
答案 0 :(得分: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
答案 1 :(得分: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.