验证模型属性大于另一个

Mic*_*les 31 activerecord ruby-on-rails

首先,让我说我对Rails 非常陌生(玩弄了一两次,但强迫自己现在用它写一个完整的项目,昨天就开始了).

我现在正在尝试验证模型属性(术语?)是否大于另一个.这似乎是一个完美的例子validates_numericality_ofgreater_than选项,但可惜的是抛出一个错误告诉我greater_than expects a number, not a symbol.如果我试图对该符号进行类型转换,.to_f我会收到undefined method错误.

这是我最终做的,我很好奇是否有更好的方法.它只是一个控制项目发布的简单系统,我们只有主要/次要版本(一点)所以浮动感觉就像这里的正确决定.

class Project < ActiveRecord::Base
    validates_numericality_of :current_release
    validates_numericality_of :next_release
    validate :next_release_is_greater

    def next_release_is_greater
        errors.add_to_base("Next release must be greater than current release") unless next_release.to_f > current_release.to_f
    end
end
Run Code Online (Sandbox Code Playgroud)

这是有效的 - 它通过了相关的单元测试(下面是为了您的观看乐趣),我只是好奇是否有一种更简单的方法 - 我本来可以试过的.

相关单元测试:

# Fixture data:
#   PALS:
#     name: PALS
#     description: This is the PALS project
#     current_release: 1.0
#     next_release: 2.0
#     project_category: 1
#     user: 1
def test_release_is_future
    project = Project.first(:conditions => {:name => 'PALS'})
    project.current_release = 10.0
    assert !project.save

    project.current_release = 1.0
    assert project.save
end
Run Code Online (Sandbox Code Playgroud)

Sim*_*tti 27

正如您所注意到的,唯一的方法是使用自定义验证器.:greater_than选项应该是一个整数.以下代码将不起作用,因为当前版本和下一版本仅在实例级别可用.

class Project < ActiveRecord::Base
  validates_numericality_of :current_release
  validates_numericality_of :next_release, :greater_than => :current_release
end
Run Code Online (Sandbox Code Playgroud)

greater_than选项的目的是根据静态常量或其他类方法验证该值.

所以,不要介意并继续使用自定义验证器.:)

  • @SimoneCarletti可以请你修改你的答案,这实际上可以在最近的Rails版本中使用,并按预期工作.因此不再需要自定义验证器. (3认同)

Bla*_*son 10

validates_numericality_of接受一个大的选项列表,其中一些可以提供proc或符号(这意味着你基本上可以传递属性或整个方法).

验证属性的数值高于另一个值:

class Project < ActiveRecord::Base
  validates_numericality_of :current_release, less_than: ->(project) { project.next_release }

  validates_numericality_of :next_release, 
    greater_than: Proc.new { project.current_release }
end
Run Code Online (Sandbox Code Playgroud)

为了澄清,任何这些选项都可以接受过程或符号:

  • :greater_than
  • :greater_than_or_equal_to
  • :equal_to :less_than
  • :less_than_or_equal_to

validates_numericality docs: http ://api.rubyonrails.org/classes/ActiveModel/Validations/HelperMethods.html#method-i-validates_numericality_of

使用带有验证的过程: http ://guides.rubyonrails.org/active_record_validations.html#using-a-proc-with-if-and-unless


dig*_*noe 6

使用Rails 3.2,您可以通过传入proc来动态地相互验证两个字段.

validates_numericality_of :next_release, :greater_than => Proc.new {|project| project.current_release }
Run Code Online (Sandbox Code Playgroud)