Alex
Alex

Reputation: 36161

MongoDB/Ruby (Mongoid): how to select only embedded documents

I have a users collection. Each user has an array of embedded documents: support requests.

class User < MyModel
  include Mongoid::Document
  embeds_many :tickets
  ...
end

class Ticket < MyModel
  include Mongoid::Document
  embedded_in :user, :inverse_of => :tickets
  ...
end

In the admin section, I make a query to select all support requests. But since the tickets collection is embedded, I can't query directly. This is what I got:

@users_with_pending_tickets = User.only(:tickets).where("tickets.status" => "Pending")

<% for user in @users_with_pending_tickets %>

    <% ticket = user.tickets.where(:status => "Pending").first %>

    <%= ticket... %>

<% end %>

This definitely looks ugly. Is there another way?

Upvotes: 1

Views: 1446

Answers (1)

bowsersenior
bowsersenior

Reputation: 12574

If you need to retrieve all tickets, you should go for a references_many relation instead of an embedded relationship.

MongoDB should eventually support 'virtual collections' to address this common issue, but for now, you have to work around this limitation.

For more info, see my answer to this similar question.

Upvotes: 2

Related Questions