ruby-on-railsruby-on-rails-3activerecordgeocodingnamed-scope

Using a Rails scope as a proxy for the scope of a related object


In our application we have two models, Stores and Offers.

Stores are geocoded using the 'geocoder' gem http://rubydoc.info/gems/geocoder

class Store < ActiveRecord::Base
  geocoded_by :address
...
class Offer < ActiveRecord::Base
  has_and_belongs_to_many :stores

The dilemma is that I'd like to be able to search for offers using the 'nearby' scope from geocoder on Offers, not just Stores. I'd like to use the Stores the Offers belong to for the nearby search. But I can't seem to get a finder to work correctly

  scope :nearby , lambda { |location, radius| 
    joins(:stores).near(location, radius)
  }  

This doesn't work as the finder is for the Offers and doesn't have the available geocoder functions.

Any ideas? I'm basically trying to use the scope of a related object in my new scope. I don't want to geocode the Offers as well, as that's just redundant data. Fairly stumped on this one


Solution

  • Just break up the logic: first get all Stores nearby and then load any Offers for those Stores. Psuedo-code:

    nearby_stores = Store.nearby(...)
    offers = Offers.where(:store_id => nearby_stores.collect { |s| s.id })