2

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?

thenapking
  • 135
  • 14
  • possible duplicate of [Rails - Validate Presence Of Association?](http://stackoverflow.com/questions/5689888/rails-validate-presence-of-association) – Don Aug 07 '15 at 14:54

1 Answers1

3

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
Jon
  • 10,678
  • 2
  • 36
  • 48