I currently have a model setup like so (-> = one-to-many):
Trader->Service->ServiceLocation<-Locations->Trader (if that makes sense)
A trader has an origin location and a service has a range, each time a new service is saved I request the new service object call an instance method .save_in_range! which takes the trader_location, loops through all locations in the database and determines the distance between the two, if it is within the range of the service it saves a relationship in the ServiceLocations table:
class Service < ActiveRecord::Base
belongs_to :trader
has_many :service_locations
has_many :locations, through: :service_locations
def save_in_range!
trader_origin = Trader.find(self.trader_id).location
locations = Location.all
locations.each do |location|
if location.distance_from(trader_origin) <= self.range
self.locations << location
end
end
end
end
My question is, do I really need to do this in this manner or am I missing some OML magic? If not is this an efficient way or am I writing awful code?