-
26
Jan
This one is pretty obvious, but I’m going to say it anyway: Do not, I repeat, do not, rely on model validations to protect your database integrity!
My example for this is a relatively minor one, but it could easily have been much worse:
During the early development of an app I worked on, we installed acts_as_taggable_on_steroids to handle tagging. The tag model, as defined in tag.rb has this line:
validates_uniqueness_of :nameMakes sense, right? Because to have duplicates of any given tag would negate the effectiveness of tagging on a whole. Well, depending on how you had things set up anyway.
Enter problem:
One feature of the app was the ability to do a bulk import of a CSV file, including tags. Any of you who have tried to do bulk imports in Rails will probably know that the first thing you do after writing a working prototype, is to factor out any and all usage of ActiveRecord, because, as beautiful and powerful as ActiveRecord is, it’s dog slow when you’re trying to import and save a few thousand records.
For those of you who haven’t realized where this is going, circumventing ActiveRecord means that all of those neat little model validations never fire. Which means duplicate tag records just kept on piling up, until we finally noticed it and I had to waste time writing a migration to consolidate the tags and their associations.
What’s the solution?
Database constraints!
Are you using validates_uniqueness_of? Add a unique index to the table!**
* No, it’s not my first mistake, but the first in what I’m sure will be many posts featuring stupid mistakes I’ve made that you should learn from.
** This message brought to you by the DBA in me. Rails is fantastic, but I miss me some SQL.
- Published by James in: Programming
- If you like this blog please take a second from your precious time and subscribe to my rss feed!
One Response to “Learn from My mistakes #1* (Model Validations)”