Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/62.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails只验证增量值_Ruby On Rails_Validation - Fatal编程技术网

Ruby on rails Rails只验证增量值

Ruby on rails Rails只验证增量值,ruby-on-rails,validation,Ruby On Rails,Validation,是否有活动记录验证来验证要添加的记录是否大于或等于数据库中已有的任何其他记录?我的想法是: class Reading < ApplicationRecord belongs_to :register validates :kwh, presence: true, numericality: {greater_than_or_equal_to: "any kwh in database"} end 课堂阅读

是否有活动记录验证来验证要添加的记录是否大于或等于数据库中已有的任何其他记录?我的想法是:

class Reading < ApplicationRecord
  belongs_to :register
  validates :kwh, presence: true, numericality: {greater_than_or_equal_to: "any kwh in database"}
end
课堂阅读
如果没有这样的方法,则使用验证\u与

class Reading < ApplicationRecord
  belongs_to :register
  validates_with IncrementalValidator
end

class IncrementalValidator < ActiveModel::Validator
  def validate(record)
    @reading = Reading.order("created_at").last
    if record < @reading
      record.errors[:base] << "This recored is not incremental"
    end
  end
end
课堂阅读record.errors[:base]只需使用自定义验证器:

课堂阅读
简短的解释:

使用Arel表格如下

self.class.where(self.class.arel_table[:kwh].gteq(42))是否存在?
#Reading.where(Reading.arel_table[:kwh].gteq(42))存在?
…类似于写:

self.class.where('readings.kwh>=?',42).是否存在?
#Reading.where('readings.kwh>=?',42)。是否存在?