I have a form with 10 attributes.
Among them, I have 4 attributes that I need to apply to what I would call an Active Record check for “conditional presence”.
I want to
- (A) if at least one is present, then the other must be present 3
- (B) still not allowed to attend (if the remaining 3 are empty, then the fourth has the right to be empty)
Here are four attributes:
- address_line_1
- postcode
- state
- Country
This means that if the user fills ONE of them, then all the others should be present. But if everything is empty, this is normal.
So far, I have only managed to enforce (A). But I do not implement (B).
, allow_blank: true 4 , (A), , , .
?
//
validates :address_line_1,
presence: true, if: :pa_subelements_mutual_presence?
length: { maximum: 100,
minimum: 3 }
validates :zipcode,
presence: true, if: :pa_subelements_mutual_presence?,
length: { maximum: 20,
minimum: 4}
validates :state,
presence: true, if: :pa_subelements_mutual_presence?,
validates :country,
presence: true, if: :pa_subelements_mutual_presence?,
length: { maximum: 50}
private
def pa_subelements_mutual_presence?
lambda { self.address_line_1.present? } ||
lambda { self.zipcode.present? } ||
lambda { self.state.present? } ||
lambda { self.country.present? }
end