Nick Shears
Nick Shears

Reputation: 1133

How to validate the absence of attributes in Rails 3?

I want to check to see if the user has ticked a "matches_applicant_address" box - Then make sure that there aren't any address details being submitted.

This works in Rails4

validates  :address_line_1, :address_line_2,
:absence => true, :if => Proc.new{matches_applicant_address.present?}

Does anybody know how I could possibly write this without the use of the absence validation method?

Upvotes: 4

Views: 1644

Answers (2)

CWitty
CWitty

Reputation: 4526

You can do

validate :address_lines_absent, if: Proc.new{ matches_applicant_address.present? }

def address_lines_absent
  errors.add :address_line_1 if address_line_1.present?
  errors.add :address_line_2 if address_line_2.present?
end

Which will make the model invalid by adding to the errors array.

Upvotes: 1

rlarcombe
rlarcombe

Reputation: 2986

In Rails 3 you can use validates_each to specify a custom validation:

validates_each :address_line_1, :address_line_2, :if => Proc.new{ matches_applicant_address.present? } do |record, attr, value|
  record.errors.add(attr, "can't be present") unless value.blank?
end

Upvotes: 4

Related Questions