title: How do I catch/solve an ActiveRecord:RecordInvalid exception caused when I save a built assocation
body: <p>I am hoping to get some help solving a problem that I'm sure many of you could avoid in your sleep.</p>
  
  <p>I have two models in a habtm relationship.  A package can have many locations, and a location can have many packages.  If my location model fails validation (due to an empty location address, for example), I get anActiveRecord:RecordInvalid exception.  I understand that I'm getting this error because when I call package.save, rails automatically calls save! on the location association.</p>
  
  <p>I'm not sure how to avoid the error or at least rescue the error.  Do any of you have any good advice, both on how to solve the problem and on Rails best practices?  </p>
  
  <p>Here is the code:</p>
  
  <pre><code>def create
      @package = current_user.package.build(params[:package])
      package_location
      if @package.save
        flash[:success] = "Package created!"
        redirect_to root_path
      else        
        render 'pages/home'
      end
    end
  
    def package_location
      gps_processing if !session[:gps_aware]
      @package.locations.build(:address =&gt; session[:address])
    end
  
    def gps_processing
      session[:address] = [params[:story][:street_address], params[:story][:city], params[:story][:state], params[:story][:country]].compact.join(', ')
    end
  
  class Package&lt; ActiveRecord::Base
  
    belongs_to :user
    has_and_belongs_to_many :locations
  
    validates         :content,   :presence   =&gt; true, 
                      :length     =&gt; {:maximum =&gt; 140}
    validates      :user_id,    :presence =&gt; true
  
    default_scope :order =&gt; 'package.created_at DESC'
  
  end
  
  class Location &lt; ActiveRecord::Base
  
    attr_accessible :lng, :lat, :address
  
    validates     :lng,       :presence   =&gt; true
    validates     :lat,       :presence   =&gt; true
    validates     :address,   :presence   =&gt; true
  
    geocoded_by :full_street_address, :latitude =&gt; :lat, :longitude =&gt; :lng  
  
    before_validation :geocode
  
    has_and_belongs_to_many :packages
  
    def full_street_address
      address
    end
  end
  </code></pre>
  
  <p>`
  Thanks in advance for your help!</p>