Saturday, May 24, 2008

attachment_fu with Optional Attachment

Note: attachment_fu has changed a bit, see the update to this post here.

attachment_fu is the most popular plugin for providing file upload to a Rails application. One thing you need to be aware of with attachment_fu is that it is meant to be used by making a model just for the attachment that will be the child relationship in a has_many or has_one. An example would be a User model that has such a relationship with an attachment_fu Avatar model. If instead you put the attachment_fu model directly in the User class and then allow that attachment to be optional, you will run into two problems:

  1. on update without an image fall down go boom
  2. on destroy without an image fall down go boom


Recently we had an application where this mistake was made and the problem wasn't noticed until the application was deployed and people started creating models without an attachment - fall down go boom.

It is, however, possible to patch attachment_fu so that it will work as an optional attachment. Information about such a patch can be found here. The provided patch only takes care of the problem of updating a record that doesn't have an attachment but the comments suggest a solution for the problem of destroying such a record as well.

With that said, Paperclip looks like the new kid on the Rails file upload block designed to avoid such problems. I think for my next file upload requirement I'll definitely take a look at Paperclip.