Validations with attachment_fu

by Damien on May 14, 2008

For a project we’ve worked on recently we were using attachment_fu to handle file uploads in a series of models in part because of how easy it makes automatic thumbnail generation. As per normal practices we had certain fields, e.g. a “title” field, set to be both required and unique, but we started getting all these errors related to the title field being missing any time we’d create a new record and upload a file.

After much fiddling around with the code it finally dawned upon us – attachment_fu’s amazing abilities create partially empty records to store thumbnails, which will obviously trip up the validators. You see, when attachment_fu creates the requested thumbnails it creates additional records in the same model and uses the parent_id to link the thumbnail(s) to the master record (the one corresponding to the original upload); however it doesn’t automatically fill in the other fields as that would be too complicated to automate, so any fields other than those attachment_fu itself uses will be blank.

The way around this unanticipated feature is to restrict the validations to only records that have a blank parent_id record, i.e. only the master records, e.g.:

validates_presence_of :title, :unless => :parent_id?
validates_uniqueness_of :title, :unless => :parent_id?

Also, bearing in mind how attachment_fu handles automatically generated thumbnails it is strongly advised to keep models with attachments highly normalized (to not have many additional fields in these models not directly used by attachment_fu), otherwise you’ll end up with a large amount of waste, which can only slow down queries.

Bookmark and Share

Other Posts That Might Interest You

  1. Custom Form Validations Without ActiveRecord
  2. DNS on GoDaddy, Email on Google Apps, Hosting on Mor.ph
  3. Ease Rails deployments with Phusion Passenger
blog comments powered by Disqus

Previous post:

Next post: