Rails - how to ignore validations for a nested object?

Viewed 44

I have a form to collect information about a Physician. Each Physician can have at least one Address but it's ok for a physician not to have any address.

Below is the relevant code from my physician.rb and model.rb files that define the respective models.

class Physician < ApplicationRecord
  belongs_to :address, optional: true
  accepts_nested_attributes_for :address

class Address < ApplicationRecord
  validates :line_1, presence: true
  validates :city, presence: true

Address has some required fields, line_1, and city

I would like to ignore the presence requirement on these fields ONLY for the Physician form.

I tried using the optional: true tag (shown in the code above) but that didn't do it.

1 Answers

You probably need to change the following line

accepts_nested_attributes_for :address

to

accepts_nested_attributes_for :address, reject_if: :all_blank

so the associated Address object will be completely ignored if all of its attributes are left blank.

Related