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
Alastair M.
Standards compliant web development with Ruby On Rails, PHP and ASP
www.kozmo.co.uk
07738 399038