删除Mongoid中的2级深嵌入文档

时间:2012-12-13 10:08:56

标签: ruby mongodb mongoid

我在运行Mongoid 2.4时在Sinatra应用程序中删除嵌入式文档时遇到了问题。以下是我模型关系的基本概述:

class User
    has_many :posts
end

class Post
    belongs_to :user
    embeds_many :comments
    embeds_many :likes, as: :likeable
end

class Comment
    field :poster_id, type: String
    embedded_in :post
    embeds_many :likes, as: :likeable
end

class Like
    field :user_id, type: String
    embedded_in :likeable, polymorphic: true
end

删除代码就像这样开始,没有问题:

# Deletes comments the user created
Post.where('comments.poster_id' => params[:userid]).each do |post|
    post.comments.where(poster_id: params[:userid]).delete_all
end

# Delete likes on posts the user created
Post.where('likes.user_id' => params[:userid]).each do |post|
    post.likes.where(user_id: params[:userid]).delete_all
end

然而,当试图删除帖子的评论时,mongoid失败了。它似乎不能深入两个层次:

# Delete likes on comments the user created (broken)
Post.where('comments.likes.user_id' => params[:userid]).each do |post|
  post.comments.likes.where(user_id: params[:userid]).delete_all
end

如何删除它们?

1 个答案:

答案 0 :(得分:2)

# Delete likes on comments the user created (not broken anymore)
Post.where('comments.likes.user_id' => params[:userid]).each do |post|
  post.comments.each {|c| c.likes.where(user_id: params[:userid]).delete_all }
end

你需要重复评论,comments.likes必须给你错误,不是吗?