I have a Rails application that lists information about local services. My objectives for this model are as follows: 1. Require the name and tag_list fields. 2. Require one or more of the tollfreephone, phone, phone2, mobile, fax, email or website fields. 3. If the paddress field has a value, then encode it with the Geokit plugin. Here is my entry.rb model:
class Entry < ActiveRecord::Base
validates_presence_of :name, :tag_list
validates_presence_of :tollfreephone or :phone or :phone2 or :mobile or :fax or :email or :website
acts_as_taggable_on :tags
acts_as_mappable :auto_geocode=>{:field=>:paddress, :error_message=>'Could not geocode physical address'}
before_save :geocode_paddress
validate :required_info
def required_info
unless phone or phone2 or tollfreephone or mobile or fax or email or website
errors.add_to_base "Please have at least one form of contact information."
end
end
private
def geocode_paddress
#if paddress_changed?
geo=Geokit::Geocoders::MultiGeocoder.geocode (paddress)
errors.add(:paddress, "Could not Geocode address") if !
geo.success
self.lat, self.lng = geo.lat,geo.lng if geo.success
#end
end
end
Requiring name and tag_list work, but requiring one (or more) of the tollfreephone, phone, phone2, mobile, fax, email or website fields does not.
As for encoding with Geokit, in order to save a record with the model I have to enter an address. Which is not the behavior I want. I would like it to not require the paddress field, but if the paddress field does have a value, it should encode the geocode. As it stands, it always tries to geocode the incoming entry. The commented out “if paddress_changed?” was not working and I could not find something like “if paddress_exists?” that would work.
Help with any of these issues would be greatly appreciated. I posted three questions pertaining to my model because I’m not sure if they are preventing each other from working. Thank you for reading my questions.
I see following problems in your code:
1) Duplicate presence checks
2) Auto and manual geo coding at the same time.
Here is a version of your code that might work:
Edit
The
required_infovalidation fails as the input data submitted by the form contains empty strings for missing fields rather than null values. Hence thephone or phone2 etc.check always returned true. I have changed the validation code to address this edge case. I am quite sure it will work now.PS:
This is a typical scenario where you should be using a debugger. Download and play with any free IDE like Aptana Radrails OR Netbeans. Once you are familiar with the tool you will be able to easily debug such issues.