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 -
errors.add_to_base "You must upload at least one image. " + self.property_images.count.to_s unless self.property_images.count > 0
My controller action to save the form/upload the images looks like -
@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
@property_image = PropertyImage.new(imageFile)
@property.property_images << @property_image
render :text => ‘saved’
render :text => ‘not saved’
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!