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


Alastair M.
Standards compliant web development with Ruby On Rails, PHP and ASP
www.kozmo.co.uk
07738 399038

On 26 Aug 2006, at 19:32, Alastair M. wrote:

def validate

@property.save!

self.property_images.count > 0 validation.

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

Many thanks in advance!

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

Alastair M. 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.


We develop, watch us RoR, in numbers too big to ignore.

On 27 Aug 2006, at 06:15, Mark Reginald J. wrote:

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


Alastair M.
Standards compliant web development with Ruby On Rails, PHP and ASP
www.kozmo.co.uk
07738 399038