thenapking
thenapking

Reputation: 145

Validate Presence of has_many Associations

Suppose I have a Person model and Address model as such:

    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

How do I validate the Person model for the presence of at least one primary and one bank address per person?

Upvotes: 2

Views: 1412

Answers (1)

Jon
Jon

Reputation: 10898

You can just write a custom validator. Something along the lines of this ought to work:

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

Upvotes: 3

Related Questions