Reputation: 2281
I`m having a problem with search query in Rails 3 application using Mongoid. My models are:
class Offer
has_many :waypoints
end
class Waypoint
belongs_to :offer
field: address
field: order, type: Integer
end
So each Offer has several Waypoints and these Waypoints has order. Waypoint with the smallest order is start point, with the biggest - destination point.
Task: We have "To" and "From" addresses. We need to find all the offers, which waypoints contain these addresses in proper order.
Problem: I can`t find useful query for it. In mongoid documentation I found smth like
Offer.where("waypoints.address" => "Berlin") but it works only if Waypoints were embedded.
Which solutions for such a problem do you know?
P.S. So I probably will create another table WaypointsCache with field like (for each offer there will be several caches with different from-to combos):
class WaypointCache
field: from
field: to
field: offer_id
end
Upvotes: 1
Views: 711
Reputation: 40277
If the goal is to find all Offers with a waypoint address of Berlin, then you have a couple of options.
Code:
waypoints = Waypoint.where(:address => "Berlin").only(:offer_id).all
offer_ids = waypoints.map(&:offer_id)
offers = Offer.any_in(:_id => offer_ids).all
Upvotes: 4