2011-07-11 57 views
1

我在使用Mongoid的Rails 3应用程序中遇到搜索查询问题。我的模特是:通过引用文档字段进行的Mongoid搜索

class Offer 
    has_many :waypoints 
end 

class Waypoint 
    belongs_to :offer 
    field: address 
    field: order, type: Integer 
end 

因此,每个优惠有几个航点,这些航点有秩序。订单最小的航点是起点,最大的目的地点。

任务:我们有“收件人”和“发件人”地址。我们需要找到所有的优惠,哪些航点以适当的顺序包含这些地址。

问题:我找不到有用的查询。在mongoid文档中,我找到了类似

Offer.where(“waypoints.address”=>“Berlin”),但只有在嵌入了Waypoints时才有效。

对于这样的问题,你知道哪些解决方案?

P.S. 所以我可能会创建一个领域的又一表WaypointsCache像(每个报价会有好几个缓存与不同对连击):

class WaypointCache 
    field: from 
    field: to 
    field: offer_id 
end 

回答

4

如果目标是找到与柏林的航点地址的所有优惠,那么你有几个选择。

  1. 将路标移到要约内嵌入。
  2. 执行两个查询,像这样:

代码:

waypoints = Waypoint.where(:address => "Berlin").only(:offer_id).all 
offer_ids = waypoints.map(&:offer_id) 
offers = Offer.any_in(:_id => offer_ids).all 
+0

与 “唯一” 的方法很好的解决方案! – makaroni4

+0

令人讨厌的常见问题的解决方案。 – xiy

相关问题