I’m stuck in a catch-22 type problem. I have an insert form for a table
that uses the validation in the model. i.e. When you click submit on the
form and haven’t filled in the required fields then you get the nice
rails error messages saying “field can not be blank”. This works fine
until I introduce some more logic.
What I’m trying to do is to validate the form first and then perform
some more validation (using google to verify the address is real) before
saving the whole thing.
The link if @bstore.valid? just renders the action add but doesn’t show
the nice error messages saying the field was blank. Any ideas?
Here’s my code so far:
def create
@bstore = Bookstore.new(params[:bookstore])
if @bstore.valid?
addresscheck = params[:bookstore][:address] + " " +
params[:bookstore][:city] + ", " + params[:bookstore][:state] + " " +
params[:bookstore][:zipcode]
address2 = ‘q=’ + addresscheck
url=‘http://maps.google.com/maps/geo?’
address = address2
address1 = URI.escape(address)
googleoutput = ‘&output=xml’
googlekey = ‘&key=mykey’
result=URI(url+address1+googleoutput+googlekey ).read
doc = Document.new(result.to_s)
root = doc.root
retstatus = root.elements[‘/kml/Response/Status/code’].text
if retstatus.to_i == 200
coordinates =
root.elements[‘/kml/Response/Placemark/Point/coordinates’].text
long1, lat1, = coordinates.split(‘,’).map { |v| v.to_f }
params[:bookstore][:latitude] = lat1
params[:bookstore][:longitude] = long1
@bookstore = Bookstore.new(params[:bookstore])
if @bookstore.save
redirect_to :action => ‘add’
flash[:notice] = ‘Store was successfully added.’
else
render :action => ‘add’
end
else
redirect_to :action => 'add'
flash[:notice] = 'We could not find that address. Please double
check the address and try again.’
end
else
render :action => ‘add’
end
end