Ruby on rails 如何针对不同的验证错误显示不同的错误消息?

Ruby on rails 如何针对不同的验证错误显示不同的错误消息?,ruby-on-rails,validation,error-handling,Ruby On Rails,Validation,Error Handling,我有一个字段用于获取用户的移动电话号码,由于没有人希望在特定字段中包含不需要的内容,我添加了验证。 这是我的验证代码 class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :r

我有一个字段用于获取用户的移动电话号码,由于没有人希望在特定字段中包含不需要的内容,我添加了验证。 这是我的验证代码

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  validates :user_name, uniqueness: true
  validates :mobile,
                  length: {minimum: 10, maximum: 10, :message => "Just those 10 digits, thanks for the extra"},
                  :numericality => {:only_integer => true, :message => "So your number has alphabets in it?"}
end
class用户“就这10个数字,谢谢你的额外”},
:numericality=>{:only_integer=>true,:message=>“那么您的数字中有字母?”
终止
我添加的验证是长度和数字,现在当我输入一个小于或大于10的数字时,它会显示第一个错误,但当我添加一些字母时,它仍然会显示长度错误


此外,我还检查了,即使我在移动字段中输入了10位数字,我仍然会显示长度错误。也许我添加的验证也有一些问题。

请澄清确切的问题是什么? 您的验证是正确的。
考虑我的代码:

class Comment < ActiveRecord::Base
    include ActsAsCommentable::Comment
    belongs_to :commentable, :polymorphic => true
    validates :title,
                    length: {minimum: 10, maximum: 10, :message => "Just those 10 digits, thanks for the extra"},
                    :numericality => {:only_integer => true, :message => "So your number has alphabets in it?"}
end

两条错误消息都存在。

问题是,当我输入超过十个字符时,它会显示长度错误,当我在其中输入字母表时,它会显示相同的错误(长度错误),而不是数字错误。我的示例是否按照您的要求工作?那么,你的意思是,如果你输入字母符号超过10,它会显示长度错误,但不会显示数字错误?你怎么试的?也许在您更改模型中的代码之后,您就不会
重新加载了或调用
有效?
或使用同一对象等?请发布一些代码示例,说明你得到了什么和你想要得到什么。不,没有。首先我添加了一长串数字,它显示了字符串错误,然后我尝试了9个数字和一个字母,然后还显示了长度错误。另外,当我尝试正确的输入时,十位数字也显示了相同的错误。每次更改移动属性后,在检查错误哈希之前,是否调用对象上的
valid?
?没有它,你就看不到任何重新验证不,我不这么认为。你能给我一个关于如何在用户创建时调用它的示例代码吗。
comment = Comment.new
comment.title = "Long text content"
comment.valid? # false
comment.errors 
# {
#     :title => [
#         [0] "Just those 10 digits, thanks for the extra",
#         [1] "So your number has alphabets in it?"
#     ]
# }