假设我有一个Person模型和地址模型:
class Address < ActiveRecord::Base
belongs_to :person
enum addresstype: {"primary" => 0, "bank" => 1}
end
class Person < ActiveRecord::Base
has_many :addresses
accepts_nested_attributes_for :addresses, allow_destroy: true
end
如何验证人员模型是否存在每人至少一个主要地址和一个银行地址?
答案 0 :(得分:3)
您可以编写自定义验证程序。根据这一点,应该有所作为:
class Person < ActiveRecord::Base
has_many :addresses
accepts_nested_attributes_for :addresses, allow_destroy: true
validate :minimum_address_requirements_met
def minimum_address_requirements_met
errors.add :addresses, 'must include a primary address' if addresses.primary.empty?
errors.add :addresses, 'must include a bank address' if addresses.bank.empty?
end
end