Multiparameter assignment validation

Have you ever realized that the default Rails date helpers allow invalid dates to be selected? I ran into an issue yesterday where one of my Teascript users attempted to select a date of November 31, 2007. That date obviously doesn’t exist. Instead of failing with a validation error, however, Rails threw a MultiparameterAssignmentErrors exception.

This is the first time I’ve run into this particular problem in Rails, and I’ve been using the framework for over two years now. Suffice it to say the odds of running into it are slim, but how should it be handled once it occurs? I found a clean, if not particularly elegant, solution in the Validates Multiparameter Assignments plugin. Once the plugin is installed, adding a single line to your model is all that’s required:

class User < ActiveRecord::Base
  validates_multiparameter_assignments
end

The plugin causes any multiparameter assignment exceptions to be surfaced as validation errors, which is exactly what I needed to happen. Why don't I think it's elegant? Simply because it takes the shotgun approach by assuming that I want to validate all multiparameter attributes. I'd prefer to specify which attributes I want validated. This is a minor nit, though. The plugin does work quite well.

There is one other customization that can be made to the plugin, but I've got to leave some surprises for you so check out the wiki page to familiarize yourself with the plugin. If you don't need the plugin now, I can pretty much guarantee you'll need it eventually.

Update: This plugin is unnecessary as of Rails 2.0.2 because invalid dates are now gracefully offset to the next valid day without causing a validation error.