I am trying to include address validation during user sign up in ruby on rails. The user has to input their address in the form of street address, city, and zipcode. I implemented some address validation in the user controller using this:
after_validation :geocode
has_secure_password
validates :address, presence: true
validate :found_address_presence
def found_address_presence
if latitude.blank? || longitude.blank?
errors.add(:address, " wasn't found.")
end
end
def full_address
[address, city, state, zip_code, 'USA'].compact.join(', ')
end
However, this always returns the error that the address was not found, even when the address is valid. I have confirmed that the addresses I inputted are real and work when the validation is removed. Why is this not working? It seems like the latitudes and longitudes are always blank, but they seem to be added appropriately when the address validation is removed.
I think the issue here is that the first line after_validation :geocode
is not filling in the longitudes and latitudes until after validation. So validate :found_address_presence
will always have blank latitudes and longitudes. If you change this first line to before_validation :geocode
, then I think it should work.