Low fire danger web development
Low Fire Danger develops web applications for businesses and startups. We design, engineer and develop user experiences to make your web application a pleasure to use.
We will also help you with your business and strategise your online presence. Giving you advice and guiding you through every step, from conception to execution. Lets talk: contact@lowfiredanger.com.au

Cascading Deletion With Carrierwave and Mongoid

Carrierwave is an awesome gem for making file uploads and image processing easy within Ruby on Rails. I’m currently testing it out with MongoDB and GridFS using Mongoid and it’s working almost seamlessly. What took me a days of work with PHP/Zend Framework now takes me an hour in Rails; just awesome, I think I might actually go and relax for a couple of hours with the time I’ve saved =).

The problem I’m having at the moment is that I’m mounting files in an embedded document; when I delete the parent document, the delete does not bubble down the the embedded document. This results in the files not been deleted from GridFS even though the parent document has been destroyed.

This is how I got around the issue. By setting a hook on the after_destroy callback method in the parent model.

Post.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Post
  include Mongoid::Document
  embeds_many :images, :class_name => "PostImage"

  after_destroy :delete_images!

 # ..
 # ..
 # ..

  def delete_images!
    images.each do |image|
      image.remove_image!
    end
  end
end
PostImage.rb
1
2
3
4
5
6
7
8
9
class PostImage
  include Mongoid::Document

  attr_accessible :image

  mount_uploader :image, PostImageUploader
  embedded_in :post, :inverse_of => :images

end