根据商店位置搜索商店的产品

时间:2017-07-16 15:25:51

标签: ruby-on-rails elasticsearch activerecord ruby-on-rails-5 searchkick

我有两个型号,产品和商店,通过库存模型关联在一起。

class Product < ApplicationRecord
  searchkick
  has_many :stocks
  has_many :stores, through: :stocks
end

class Store < ApplicationRecord
  searchkick locations: [:location]
  belongs_to :user
  has_many :stocks
  has_many :products, through: :stocks
end

使用Searchkick(Elastic)或ActiveRecord我想搜索产品并获得与查询匹配的产品,包括具有它们的商店,按这些商店的距离排序(订单部分不是很重要)。

有谁知道我怎么做到这一点?

1 个答案:

答案 0 :(得分:0)

使用ActiveRecord的最简单方法是获取所有匹配搜索的产品,并在下一个查询中检索具有以下产品的商店:

products = Product.where(your_search_params)
stores = Stores.joins(:stocks).where('stocks.product_id IN (?)', products.ids)
相关问题