Rails : how to handle : some field’s presence is mandory in some context but not always

You might stuble upon some situation like “how to handle : some field’s presence is mandory in some context but not always”. It is how I decided to handle such situation

# in controller/action
phone_params = {
    phone: phone_number,
    phone_number_required: true
}

if @user.update_attributes(phone_params)
  # do stuff

 

and


# in models/user.rb
attr_accessor :phone_number_required

# Only validates if Phone field is required
#   or phone is not required but content needs to be validated
# For example
#   When user is signed up; no phone field passed;
#     in that case no validation
#   When in introduction page; phone is required
#     phone_number_required = true; # need to be set
#   When in child profile edit page
#     phone_number is not required but value if present needs to be validated
# #
def phone_validator
  if phone_number_required || (!phone_number_required && self.phone.present?)
   validation = SmsService.validate_phone_number(self.phone)
   unless validation.is_valid?
     self.errors.add(:phone, validation.message)
   end
  end
end

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s