使用 Rails 作用域作为相关对象作用域的代理

发布于 2024-11-24 01:19:22 字数 637 浏览 2 评论 0原文

在我们的应用程序中,我们有两个模型:商店和优惠。

使用“geocoder”gem 对商店进行地理编码 http://rubydoc.info/gems/geocoder

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

困境是我希望能够使用地理编码器中的“附近”范围搜索优惠,而不仅仅是商店。我想使用优惠所属的商店进行附近的搜索。但我似乎无法让查找器正常工作。

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

这不起作用,因为查找器用于优惠并且没有可用的地理编码器功能。

有什么想法吗?我基本上是尝试在新范围中使用相关对象的范围。我也不想对优惠进行地理编码,因为这只是冗余数据。相当难倒这个

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

Saygoodbye 2024-12-01 01:19:23

只需打破逻辑:首先获取附近的所有商店,然后加载这些商店的任何优惠。伪代码:

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

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 })
ㄟ。诗瑗 2024-12-01 01:19:22

我想你想要:

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文