Topic: Custom callback
I'm building an app that allows users to set their current town and hometown from a huge table (millions of records), so I implemented it without relations (it's faster than using relations, even with cache). I used some custom code to normalize inputs and discard invalid 'city' IDs.
The thing is, how good is my code? I'm new to Ruby/Rails, and I was wondering if I'm not doing things the hard (or wrong) way.
class UserProfile < ActiveRecord::Base
attr_accessible :town_current, :town_home, :town_current_id, :town_home_id
# Callbacks
before_validation :town_ids_exist
def town_ids_exist
validate_town 'town_current', self.town_current_id
validate_town 'town_home', self.town_home_id
end
def validate_town(field, id)
town = town_exists id
if town.nil?
send "#{field}_id=", nil
send "#{field}=", nil
else
send "#{field}=", town.city
end
end
def town_exists(id)
Location.find_by_id(id)
end
end