Check active Rails 4 record - conditionally checks for 4 attributes, if at least one is present, while no one is present

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? # method to help set validates on mutually dependent for presence for postal address
      lambda { self.address_line_1.present? }  ||
      lambda { self.zipcode.present? }         ||
      lambda { self.state.present? }         ||
      lambda { self.country.present? }
    end
0
1

, . , .

validate :all_or_none

private
    def all_or_none
        errors[:base] << "all or nothing, dude" unless
            (address_line_1.blank? && zipcode.blank? && state.blank? && country.blank?) ||
            (!address_line_1.blank? && !zipcode.blank? && !state.blank? && !country.blank?)
    end

all_or_none , .

+1

All Articles