Conditional validation?

Hi, I have followed the tutorial in the AWDWR book for uploading an
image. This involves adding the following field to the form.
<%= f.file_field :uploaded_picture %>

The model then goes to work on the data to store it in the database,
with the following:

validates_format_of :content_type,
:with => /^image/,
:message => “-- you can only upload pictures”

def uploaded_picture=(picture_field)
self.name = base_part_of(picture_field.original_filename)
self.content_type = picture_field.content_type.chomp
self.data = picture_field.read
end

def base_part_of(file_name)
File.basename(file_name).gsub(/[^\w._-]/, ‘’ )
end

Now, all of this works fine, but I would like the picture upload to be
an optional feature, but if the user fills in the form and leaves the
field blank, the following error is displayed

undefined method `original_filename’ for “”:String

I’ve tried adding "unless picture_field.empty/nil? to the
uploaded_picture action, but I can’t get anything that works for both an
image being supplied and no image being supplied.
Can anyone suggest a way to get around this? Thanks.

Dan S. wrote:

validates_format_of :content_type,
:with => /^image/,
:message => “-- you can only upload pictures”

I’ve tried adding "unless picture_field.empty/nil? to the

Try “unless picture_field.blank?” and add “:allow_blank => true” to the
validation line.

If you are using Rails earlier than version 2, then make that
“:allow_nil => true”, though I’m not sure if that will be as successful.

Thanks, that seems to have worked:)

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs