【问题标题】:Using a Rails scope as a proxy for the scope of a related object使用 Rails 范围作为相关对象范围的代理
【发布时间】:2011-07-14 15:26:54
【问题描述】:

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

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

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

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

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

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

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

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 activerecord geocoding named-scope


    【解决方案1】:

    我想你想要:

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 这确实有效,但将其拆分为两个 SQL 调用并且看起来不优雅。不过,谢谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-13
      • 2014-10-16
      • 2011-10-09
      • 2012-10-22
      • 2020-09-04
      • 2015-06-25
      • 1970-01-01
      相关资源
      最近更新 更多