order of saving/validating

Hi guys,

I’m trying to do some validation on an image upload. Basically I have a model, Property, which has_many :property_images. I need to check that one image has been uploaded at least and so it was suggested I checked the number of images uploaded - @property.property_images.count > 0. Makes sense.

I’ve added a validation on my Property model, like -

def validate

errors.add_to_base "You must upload at least one image. " + self.property_images.count.to_s unless self.property_images.count > 0

end

My controller action to save the form/upload the images looks like -

def create

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

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

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

file_id = file_id.to_i

if file_id >= 1 and file_id <= 3

unless imageFile[“filename”].nil?

@property_image = PropertyImage.new(imageFile)

@property.property_images << @property_image

end

end

end

@property.save!

render :text => ‘saved’

rescue ActiveRecord::RecordInvalid

render :text => ‘not saved’

end

The problem is occuring on the save. It seems like rails is validating the Property model first before the images have been uploaded and as such, it will never pass the self.property_images.count > 0 validation.

Does anyone have any suggestions on how I can get round this problem?

Many thanks in advance!

Alastair

Still trying to get my head round how this can work! does anyone have any ideas?

Any help would be well appreciated!

Thanks,

Alastair

Alastair Moore wrote:

The problem is occuring on the save. It seems like rails is validating the Property model first before the images have been uploaded and as such, it will never pass the self.property_images.count > 0 validation.

Try using property_images.size, which will return the length of the in-memory array, rather than property_images.count which will be counting the zero objects in the database prior to saving.

Hi Mark,

Brilliant - worked a treat.

Thanks!

Alastair