Ignore Empty File Uploads with attachment_fu (Multiple files)

Hi there,

I have multiple file uploads working with attachment_fu, however if
one of the file fields is empty then it throws a validation error.
Removing the validation results in an empty (nil) record being
created.

I’d like to be able to just ignore the empty file field and save the
ones present.

Any help or advice would be much appreciated.

Many thanks,
Will

--------------------------------------------------- photo.rb

class Photo < ActiveRecord::Base
belongs_to :album
has_attachment :content_type => :image,
:storage => :file_system,
:max_size => 5000.kilobytes,
:resize_to => ‘600x600>’,
:thumbnails => { :thumb => ‘150x150>’, :stamp =>
‘75x75>’ },
:path_prefix => ‘public/images’,
:processor => ‘rmagick’

validates_as_attachment
end

--------------------------------------------------- album.rb

class Album < ActiveRecord::Base
has_many :photos, :dependent => :destroy
after_update :save_photos

def image_attributes=(image_attributes)
image_attributes.each do |attributes|
if attributes[:id].blank?
photos.build(attributes)
else
photos = photos.detect { |t| t.id == attributes[:id].to_i}
photos.attributes = attributes
end
end
end

def save_photos
photos.each do | photo |
photo.save(false)
end
end
end

---------------------------------------------------

albums_controller.rb
class AlbumsController < ApplicationController

… Other REST actions

def edit
@collection = Collection.find(params[:id])
end

def update
@album = Collection.find(params[:id])
if @album.update_attributes(params[:album])
flash[:notice] = “New photos saved”
redirect_to album_path(@album)
else
flash[:error] = “Something went wrong”
render :action => ‘edit’
end
end
end

--------------------------------------------------- views/albums/

edit.html.erb
<%= error_messages_for ‘album’ %>

<% form_for (@album, :html => { :multipart => true }) do |f| %>
<% fields_for “album[image_attributes][]”, @album.photos do |
photo_form| %>


<%= photo_form.file_field :uploaded_data, :index => nil %>
Name: <%= photo_form.text_field :name, :index => nil %>



<%= photo_form.file_field :uploaded_data, :index => nil %>
Name: <%= photo_form.text_field :name, :index => nil %>


<% end %>

<%= submit_tag ‘save’ %>
<% end %>

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