Uploading multiple files with paperclip

Here is my code that worked well to upload multiple file using paperclip:
We can achieve using nested attributes or using normal easy method.

The following code shows normal method:

User.rb

has_many :images, :dependent => :destroy

Image.rb

has_attached_file :avatar, :styles => { :medium => “300×300>” }

belongs_to :user

users/views/new.html.erb

<%= form_for @user, :html => { :multipart => true } do |f| %>

...... 
 ....

<%= file_field_tag :avatar, multiple: true %>

<% end  %>

Users_controller:

…..

    if @user.save
     # params[:avatar] will be an array.
     # you can check total number of photos selected using params[:avatar].count
      params[:avatar].each do |picture|      
    
        @user.images.create(:avatar=> picture)
        # Don't forget to mention :avatar(field name)
    
      end
    end

Thats it. images got uploaded, this may not be the good way but it works.

Leave a Comment