mongoid:过滤嵌套文档



我正在构建一个安息的博客API,其中有两个模型:

class Article
  include Mongoid::Document
  include Mongoid::Timestamps
  embeds_many :comments
  ...
 end

 class Comment
  include Mongoid::Document
  include Mongoid::Timestamps
  field :status, type: String
  ...
 end

默认情况下Comment#statusnew。当管理员批准评论时,状态将切换为published

在任何情况下,我都不想将未批准的评论运送到前端。我如何查询所有文章的已发布仅使用一个查询来注释?

这就是您要寻找的

@articles = Article.where("comments.status": "published").all

在此处阅读有关在嵌套字段上查询的更多信息