title: Efficient looping and saving for a many to many relationship?
body: <p>I currently have a model setup like so (-> = one-to-many):</p>
  
  <p>Trader->Service->ServiceLocation&lt;-Locations->Trader  (if that makes sense)</p>
  
  <p>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:</p>
  
  <pre><code>class Service &lt; 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) &lt;= self.range
              self.locations &lt;&lt; location
            end
        end
      end
  end
  </code></pre>
  
  <p>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?</p>