【问题标题】:How to validate numericality and inclusion while still allowing attribute to be nil in some cases?如何在某些情况下仍然允许属性为 nil 的同时验证数字性和包含性?
【发布时间】:2012-05-22 11:06:03
【问题描述】:

在 Rails 应用程序中,我在模型上有几个整数属性。

用户应该能够创建记录并将这些属性留空。

或者,如果用户为这些属性输入值,则应验证它们的数值并在一定范围内。

在模型中我有这样的东西

validates_presence_of :name    
validates_numericality_of :a, :only_integer => true, :message => "can only be whole number."
validates_inclusion_of :a, :in => 1..999, :message => "can only be between 1 and 999."

如果我现在使用要保存的最低要求属性进行测试:

factory :model do
  sequence(:name) { |n| "model#{n}" }
end

it "should save with minium attributes" do
  @model = FactoryGirl.build(:model)
  @model.save.should == false
end

我明白了

Validation failed: a can only be whole number., a can only be between 1 and 999.

如何仅在为 :a 提供值的情况下验证数字性和包含性,同时在某些情况下仍允许 :a 为 nil?

谢谢

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    您可以将:allow_nil => true 添加到您的validates_numericality_of

    validates_numericality_of :a, :only_integer => true, :allow_nil => true, 
        :message => "can only be whole number."
    

    如果您只想使用一个验证,也可以使用greater_than_or_equal_toless_than_or_equal_to 选项:

    validates_numericality_of :a, :only_integer => true, :allow_nil => true, 
        :greater_than_or_equal_to => 1,
        :less_than_or_equal_to => 999,
        :message => "can only be whole number between 1 and 999."
    

    【讨论】:

      【解决方案2】:

      应该是:

      validates_numericality_of :a, :only_integer => true, :message => "can only be whole number.", :allow_nil => true
      

      第二次验证相同

      【讨论】:

      • 谢谢,这正是我所需要的。我已经为 Shadwell 的 DRY 代码提供了答案。很遗憾我不能将两者都标记为正确。
      猜你喜欢
      • 2023-03-25
      • 1970-01-01
      • 2014-12-04
      • 2012-06-18
      • 1970-01-01
      • 1970-01-01
      • 2011-03-01
      • 1970-01-01
      • 2014-08-09
      相关资源
      最近更新 更多