1

I'm trying to create a form that has 3 models (1 for the actual form, 1 for other entries and another for the uploaded archives). I want to use jQuery File Upload gem to upload my PDFs to the server, but I'm also using the ActiveAdmin gem that handles this forms.

How can I create a multi-upload file input and add that through my Files model inside ActiveAdmin?

I should have:

  • Validates if the file is a PDF
  • Validates his size
  • Submit everything together with the form ( if the form has an error, don't upload but keep the files inside the input )

1 Answer 1

2

For a form with multiple uploads you can try this:

# active admin
form do |f|
  f.inputs "ModelName" do 
    f.input :name
  end
  f.has_many :attachments do |ff|
    ff.input :path
  end
end

# your_model.rb
attr_accessible :attachments_attributes
has_many :attachments

# your_model.rb (add after relations)
accepts_nested_attributes_for :attachments, :allow_destroy => true

see also: accept nested attributes for has_many relationship

Use of rails validators will hinder the form from being saved if not passed.

# attachment.rb  
validates :check_size 
validates :check_if_pdf 

def check_size
  errors.add :path, "Size is NOT ok" if self.size < XXX
end

def check_if_pdf 
  errors.add :path, "File is NOT pdf" unless self.path.to_s.split('.').last == 'pdf'
end

Not sure about Paperclip...Carrierwave is awesome as well and if you are open to that gem you can try this:

# attachment.rb
mount_uploader :path, MyUploader

# app/uploaders/my_uploader.rb
class MyUploader < CarrierWave::Uploader::Base
  storage :file  # For local storage
  #storage :fog  # If using S3

  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  def filename
    @name ||= "#{File.basename(original_filename, '.*')}" if original_filename.present?
  end
end

Carrierwave has an extension_white_list method that you can try to validate that its a PDF document

 # uploaders/my_uploader.rb
 def extension_white_list
   %w(pdf jpg jpeg gif png csv )
 end
Sign up to request clarification or add additional context in comments.

3 Comments

That was very helpful, after that, how can I upload the multiple files with Paperclip and the activeAdmin gem?
Ok, added some lines in case you wanna change to Carrierwave.
Thanks again, can I add you on Skype? I'm really new to the Rails world.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.