I’ve been having problems deleting en embedded document in my Sinatra application, running Mongoid 2.4. Here is a basic overview of my models’ relationships:
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
The deletion code starts like this, without problems:
# 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
However, when trying to delete likes of comments of posts, mongoid fails. It seems it cannot go two levels deep:
# 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
How can I delete them?
You need to iterate on the comments,
comments.likesmust be giving you error, is it not?