开发者

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

开发者 https://www.devze.com 2023-02-02 18:35 出处:网络
I have a users collection. Each user has an array of embedded documents: support requests. class User < MyModel

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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消