The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
Handling Invalid Dates with ActiveRecord Date Helpers

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Bob Silva

Posts: 94
Nickname: bobsilva
Registered: Feb, 2006

Bob Silva is a Rails Developer for the UMESD
Handling Invalid Dates with ActiveRecord Date Helpers Posted: Feb 28, 2006 6:41 PM
Reply to this message Reply

This post originated from an RSS feed registered with Ruby Buzz by Bob Silva.
Original Post: Handling Invalid Dates with ActiveRecord Date Helpers
Feed Title: Rails Video Tutorials
Feed URL: http://www.railtie.net/xml/rss/feed.xml
Feed Description: A growing collection of screencasts that show you how to use the many facets of the wonderful world of rails.
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Bob Silva
Latest Posts From Rails Video Tutorials

Advertisement
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
    init_client_lookup_tables
    render :action => 'new'
  end
end

In model.rb:

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

Read: Handling Invalid Dates with ActiveRecord Date Helpers

Topic: Ruby lets me use my brain again Previous Topic   Next Topic Topic: Those who can, do. Those who can't, critique(?)

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use