【问题标题】:Rails model scope based on associated model基于关联模型的 Rails 模型范围
【发布时间】:2014-09-23 07:26:45
【问题描述】:

我这里有两个相关模型:InventoryItemStore

class InventoryItem < ActiveRecord::Base
  belongs_to    :store
  include Tire::Model::Search
  include Tire::Model::Callbacks

  def self.search(params)
    tire.search(load: true, :per_page => 40) do
      query { string params[:query], default_operator: "AND" } if params[:query].present?
    end
  end
end


class Store < ActiveRecord::Base
  geocoded_by :address
  after_validation :geocode, :if => lambda{ |obj| obj.address_changed? }

  has_many  :inventory_items
end

我想从当前用户附近的商店搜索inventory_items(用户也使用geocoder gem 进行地理编码)。我正在考虑的方法是以某种方式确定模型的范围,但我不确定如何实现。以下是我通常如何在控制器中查找附近商店的方法:

@stores = Store.near([current_user.latitude, current_user.longitude], current_user.distance_preference, :order => :distance)

有没有办法在我的 InventoryItem 模型上基于其关联商店是否在当前用户附近进行:local 范围?或者,有没有办法用elasticsearch实现我的目标?提前致谢!

【问题讨论】:

    标签: ruby-on-rails elasticsearch tire


    【解决方案1】:

    有几种方法可以实现这一点。我认为最简单的开始方式是这样的:

    class Store < ActiveRecord::Base
       scope :for_user, -> {|user| near([user.latitude, user.longitude], user.distance_preference, :order => :distance)}
    end
    

    这会让你打电话

    Store.for_user(whatever_user)
    

    在库存上,我也会尝试按商店查找:

    class InventoryItem < ActiveRecord::Base
      scope :for_stores, -> {|stores| where(store_id: stores.map(&:id))}
    end
    

    我不熟悉您那里的搜索引擎,但如果它进行活动记录范围嵌套,您应该能够执行以下操作:

    InventoryItem.for_stores(Store.for_user(whatever_user)).search(...)
    

    【讨论】:

    • 谢谢您,测试了您建议的两个范围,它们都可以工作。还像答案的最后一行一样对它们进行了测试。不幸的是,我的搜索没有被限定,但这是与搜索库相关的另一个问题。
    猜你喜欢
    • 2012-05-11
    • 2017-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-23
    • 1970-01-01
    相关资源
    最近更新 更多