我在运行 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
我怎样才能删除它们?