0

I am creating an app which has a model "Gallery". I am having another model which is "GalleryPhoto". The relationship is: Gallery has_many GalleryPhoto and GalleryPhoto belongs_to Gallery.

Following are the models i have created:

class Gallery < ActiveRecord::Base
  has_many :gallery_photos, dependent: :destroy
end

class GalleryPhoto < ActiveRecord::Base
  belongs_to :gallery
  has_attached_file :photo
  validates_attachment_content_type :photo, :content_type => ['image/jpeg', 'image/jpg', 'image/png']
end

Now after i am creating the Gallery, on its index page i am having the link to add photos that will open a page to add photos. On this page i will be able to add photos using paperclip.

This is my new.html.erb for gallery_photo:

<%= form_for @gallery_photo,html: { multipart: true},url: gallery_photos_path,method: :post do |f| %>

              <%= f.hidden_field :gallery_id, value: params[:gallery_id]%>
              <%=f.file_field :photo%>
              <%= f.submit "Start Upload",class: "btn btn-primary actions"%>
        <% end %>

I am able to Upload single photo. But i am not getting how to upload multiple photos using paperclip. Any help will me appreciated.

Vishal
  • 707
  • 1
  • 8
  • 30
  • 1
    Possible duplicate of [Uploading multiple files with paperclip](http://stackoverflow.com/questions/11605787/uploading-multiple-files-with-paperclip) – uzaif May 06 '16 at 04:11

1 Answers1

0

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 => "300x300>" }

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.

Community
  • 1
  • 1
Shyam Bhimani
  • 1,310
  • 1
  • 22
  • 37
  • Thanx for the reply. Upto my understanding this will create a user also, right? But i want to add photos in the existing gallery. I dont want to create new gallery on uploading photos. – Vishal May 06 '16 at 04:29