[英]Rails sort child model based on parent model distance calculation
我有一个product
模型和一个shop
模型。 两者之间的关系是商店has_many
和产品belongs_to
shop。
shop模型具有两个字段longitude
和latitude
用于使用geokit-rails进行距离计算。 我已经成功地使用以下方法按照任何给定的经度和纬度对距离进行了分类:
Shop.by_distance(origin:[params[:latitude], params[:longitude]]).sort_by{|s| s.distance_to([params[:latitude], params[:longitude]])}
问题出在产品上。 还需要根据最近的商店位置对产品进行分类。 我搜索了一下,发现可以从父级属性中对子模型进行排序,如下所示:
Product.joins(:shop).order('shops.name')
订单功能仅在模型字段中提供。 如何分类产品以计算商店距离。
请帮忙。
看看使用:through
的文档-这应该正是您所需要的。
因此Product
看起来像:
class Product < ActiveRecord::Base
belongs_to :shop
acts_as_mappable through: :shop
...
end
您的查询将类似于:
Product.joins(:shop).by_distance(origin: [params[:latitude], params[:longitude]])
如果您已经可以对商店进行过滤和排序
@shops = Shop.by_distance(origin:[params[:latitude], params[:longitude]]).sort_by{|s| s.distance_to([params[:latitude], params[:longitude]])}
这将根据距离从每个商店获得所有产品:
@closest_products = @shops.map(&:products)
如果要淘汰重复的产品,请改用以下方法:
@closest_products = @shops.map(&:children).flatten.uniq
您可以尝试其他方法(我尚未对此进行测试):
@closest_products = Product.where(shop: @shops)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.