Rails 验证,知道哪个字段是无效的吗?

Rails validation, knowing which field is invalid?

我有一个模型很好用。

class Product < ActiveRecord::Base
  validates_format_of :field1, with: /\A[0-9\+\-\/\s]+\Z/, allow_nil: true
  validates_format_of :field2, with: /\A[0-9\+\-\/\s]+\Z/, allow_nil: true
end

我在数据库中的某些条目无效。这些是较旧的条目。 我想 运行 找到这些无效条目的种子

Product.all.each do |product|
  next if product.valid?
  # 
end

我想清除无效的属性。让我说,产品 1 在 field1 中的值 test 是无效的。现在我想清除这个字段,而且只有这个。

如何找到无效的字段?像 product.field1.valid?

Railsapi可以通过ActiveModel::Errors#get方法按键获取错误信息:

Product.all.each do |product|
  product.valid? # => run validation callbacks

  product.errors.messages          # => {:field1=>["cannot be nil"]}
  product.errors.get(:field1)      # => ["cannot be nil"]
  product.errors.get(:field2)      # => nil

  # `include?` and `has_key?` works too(it's aliases)
  product.errors.messages          # => {:field1=>["cannot be nil"]}
  product.errors.include?(:field1) # => true
  product.errors.include?(:field2) # => false

  # 
end

这样做很容易,但是关于性能有几点需要牢记:

  1. 只想将所有产品加载到内存中,然后迭代它们,
  2. 如果可能的话,你不应该尝试一一更新。

这可能是一个可以接受的解决方案:

invalid_ids = []

Product.find_each(batch_size: 200) do |product|
  if !product.valid?
    if product.errors.include?(:field_1)
      invalid_ids << product.id
    end
  end
end

Product.where(id: invalid_ids).update_all(field_1: nil)

您可以使用 valid? and can also check for errors

检查和验证模型及其属性
Product.all.each do |product|
 if  !product.valid? and !product.errors[field1].blank?
    ##do something if product is not valid and there is error in attribute that you may want to check
 end
end