Handling Invalid Dates with ActiveRecord Date Helpers 3

Posted by Bob Silva Thu, 23 Feb 2006 03:42:00 GMT

If you've worked with the model based date helpers in Rails (date_select and datetime_select), then you may know that selecting an invalid date throws an exception deep within ActiveRecord. A lot of users assume they can handle this in the model validation, but due to the way ActiveRecord handles multi-parameter input values, it will raise an exception if an invalid date is input. Here's some sample code of how you can catch and handle this exception without affecting the user experience too much.
In controller.rb:

def create
  begin
    @client = Client.new(params[:client])
  # Catch the exception from AR::Base
  rescue ActiveRecord::MultiparameterAssignmentErrors => ex
    # Iterarate over the exceptions and remove the invalid field components from the input
    ex.errors.each { |err| params[:client].delete_if { |key, value| key =~ /^#{err.attribute}/ } }
    # Recreate the Model with the bad input fields removed
    @client = Client.new(params[:client])      
  end
    
  if @client.save
    flash[:notice] = 'Client was successfully created.'
    redirect_to :action => 'list'
  else
    render :action => 'new'
  end
end

In model.rb:

validates_presence_of :date_field_name, :message => 'must be a valid date'

Comments

Leave a response

  1. Paul 5 months later:
    Thanks for the solution, works great.
  2. mek 7 months later:
    there is always a good solution in RAILS! :D
  3. topfunky 9 months later:
    There is also a plugin that moves these errors into the regular errors hash: http://wiki.rubyonrails.org/rails/pages/Validates+Multiparameter+Assignments
Comments