handling errors on multiple file upload

Hello guys,

I’ve got the following models:

class Asset < ActiveRecord::Base

end

class PropertyImage < Asset

belongs_to :property

validates_file_format_of :filename, :in => [“gif”, “png”, “jpg”]

file_column :filename, :magick => {

:versions => { “thumb” => “50x50”, “medium” => “220x280” }

}

end

class Property < ActiveRecord::Base

has_one :property_profile, :foreign_key => ‘property_id’, :dependent => :destroy

has_many :property_images, :foreign_key => ‘fk_id’, :dependent => :destroy

belongs_to :property_seller

validates_associated :property_profile

end

and I have the following method in a controller:

def sell

@property = Property.new(params[:property])

@property_profile = @property.property_profile = PropertyProfile.new(params[:property_profile])

return unless request.post?

@property.save!

params[:property_image].each do |file_id,attr|

file_id = file_id.to_i

if file_id >= 1 and file_id <= 3

image = PropertyImage.new(attr)

unless image[‘filename’] == nil

image.fk_id = @property.id

image.title = @property_profile.title

image.save

end

end

end

flash[:notice] = “Property saved”

redirect_to :action => ‘list’

rescue ActiveRecord::RecordInvalid

render :action => ‘sell’

end

and the image part of my view -

<% for i in 1…3 %>

<label for="property_image_<%= i %>_filename">Image</label><br />

<input id="<%= "property_image_#{i}_filename_temp" %>" name="<%= "property_image[#{i}][filename_temp]" %>" type="hidden" />

<input id="<%= "property_image_#{i}_filename" %>" name="<%= "property_image[#{i}][filename]" %>" size="30" type="file" />

<% end %>

I’m trying to handle file validation - basically the user MUST upload one image at least. Now the way it’s set out above, the property will save, however if there’s an issue with the image (ie. it’s missing or in the wrong format), then that property will already have been saved. What I need to do is handle the error before saving everything. Any suggestions how I can do this?

Thanks!

Alastair