开发者

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 doe开发者_如何学运维sn'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


I think you want:

class Offer < ActiveRecord::Base
  has_and_belongs_to_many :stores
  scope :nearby, lambda { |location, radius| 
      joins(:stores).merge(Store.near(location, radius))
    }
end


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 })
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜