在单个实例上,验证会生成如下内容:
foo = Foo.new(price: -2)
foo.valid?
foo.errors
=> #<ActiveModel::Errors:0x00007fc66e670430
@base=#<Foo:0x00007fc6503f8658 id: nil, price: nil,
@details={:price=>[{:error=>:greater_than_or_equal_to, :value=>-0.2e1, :count=>0}]},
@messages={:price=>["must be greater than or equal to 0"]}>
使用更新方法时是否存在获取错误的方法?:
Foo.update([1, 2, 3], [{ price: 10 }, { price: -20 }, { price: 3 }])
谢谢!
答案 0 :(得分:1)
以下是如何从Model.update(...)
方法收集错误的示例:
# first create a payload with ids and attributes
payload = { 1 => { price: 10 }, 2 => { price: -20 } }
# next update records
result = Foo.update(payload.keys, payload.values)
# the update method returns processed records
# in case of array it will return array of records
# iterate over all objects and find invalid
with_errors = result.map { |r| !r.errors.any? ? nil : r }.compact
# after compact the with_errors variable contains only invalid records.
答案 1 :(得分:0)
我最后做了什么:
class FooUpdateService
attr_reader :errors
def update(ids, values)
self.errors = ActiveModel::Errors.new(Foo.new)
Foo.update(ids, values).select(&:invalid?).each { |invalid_foo| self.errors.merge!(invalid_foo.errors) }
end
private
attr_writer :errors
end