我有两个普通的 Ruby 类:Account 和 Contact。我正在使用简单表单的 simple_form_for 和 simple_fields_for 来创建嵌套属性。我希望满足以下验证要求:
ActiveModel 似乎不再包含 validates_linked 方法,因为使用该方法会导致未定义的方法错误。我考虑过需要 ActiveRecord::Validations,但这导致了一系列各种错误(例如,未定义的方法“marked_for_destruction?”)
我还考虑过在 Account 类上定义 validate 并调用 valid?在关联的对象上,但这只会阻止表单在父对象上也出现错误时提交。
validate do |account|
account.contact.valid?
# required for form to fail
errors.add(:base, "some error")
end
有什么我不知道的东西可以解决这个问题吗?谢谢。
我最近(这个问题被提出 7 年后!)遇到了同样的问题,并通过基于 ActiveRecord 实现
AssociatedValidator
解决了它。
我只是将其包含在 config/initializers
文件夹中:
module ActiveModel
module Validations
class AssociatedValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
if Array(value).reject { |r| valid_object?(r) }.any?
record.errors.add(attribute, :invalid, **options.merge(value: value))
end
end
private
def valid_object?(record)
record.valid?
end
end
module ClassMethods
def validates_associated(*attr_names)
validates_with AssociatedValidator, _merge_attributes(attr_names)
end
end
end
end
现在您也可以在 ActiveModel 中使用
validates_associated
。
class Person
include Virtus
include ActiveModel::Model
attribute :address, Address, :default => Address.new
validate :address_valid
private
def address_valid
errors.add(:base, 'address is not valid') unless address.valid?
end
end
class Address
include Virtus::ValueObject
include ActiveModel::Validations
attribute :line_1, String
attribute :line_2, String
validates :line_1, :presence => true
validates :line_2, :presence => true
end
如果将对象传递给
simple_fields_for
,错误会显示在表单中:
= form.simple_fields_for person.address do |af|
= af.input :line_1
另一个选项是覆盖的
valid?
:
def valid?
super & address.valid?
end
注意它的
&
而不是 &&
,因此如果第一个返回 false,条件不会短路。
借鉴@coorasse的想法,我检查了ActiveRecord中的实现,发现它也应该与ActiveModel兼容。
我们可以简单地编写一个扩展 ActiveRecord::Validations::AssociatedValidator 的新逻辑,而不是重复相同的逻辑。
这是我发现的最简单的解决方案,而且效果非常好。
# app/validators/associated_validator.rb
# Custom validator to ensure associated objects are valid
class AssociatedValidator < ActiveRecord::Validations::AssociatedValidator
end
# Your model
class Book
include ActiveModel::Validations
validates :author, associated: true # Enable validation for associated objects
end