Translate

September 15, 2015

Uploading Multiple Images using CarrierWave

How to upload multiple image by selecting "ctrl + selction key" at same time.

CarrierWave
This gem provides a simple and extremely flexible way to upload files from Ruby applications.
This gem has convenient support for multiple file upload fields.

Following are the steps:
For Complete Source code click here

In Rails, add it to your Gemfile:


gem 'carrierwave'
 
bundle install
 
rails generate uploader photo

Create post scaffold

rails generate scaffold post title:string

Create post_attachment scaffold

post_attachment post_id:integer photo:string
 
rake db:migrate

In post.rb

class Post < ActiveRecord::Base
  has_many :post_attachments
  accepts_nested_attributes_for :post_attachments
end

In post_attachment.rb

class PostAttachment < ActiveRecord::Base
   mount_uploader :photo, PhotoUploader
   belongs_to :post
end

In post_controller.rb

def show
  @post_attachments = @post.post_attachments.all
end

 def new
   @post = Post.new
   @post_attachment = @post.post_attachments.build
 end
 
 def create
   @post = Post.new(post_params)
   respond_to do |format|
     if @post.save
       params[:post_attachments]['photo'].each do |a|
         @post_attachment = @post.post_attachments.create!(:photo => a)
       end
      format.html { redirect_to @post, notice: 'Post was successfully created.' }
     else
      format.html { render action: 'new' }
    end
   end 
 end
 
 private
  def post_params
    params.require(:post).permit(:title, post_attachments_attributes: [:id, :post_id, :photo])
  end

In views/posts/_form.html.haml

 = form_for(@post, :html => { :multipart => true }) do |f|
  .field
    = f.label :title
    = f.text_field :title
  = f.fields_for :post_attachments do |p|
    .field
      = p.label :photo
      = p.file_field :photo, :multiple => true, name: "post_attachments[photo][]"
  .actions
    = f.submit
 

In views/posts/show.html.haml

%p#notice= notice
%p
  %strong Title:
  = @post.title
- @post_attachments.each do |p|
  = image_tag p.photo_url
  = link_to "Edit Attachment", edit_post_attachment_path(p)
= link_to 'Edit', edit_post_path(@post)
|
\#{link_to 'Back', posts_path}
 
Update form to edit an attachment views/post_attachments/_form.html.haml

= image_tag @post_attachment.photo
= form_for(@post_attachment) do |f|
  .field
    = f.label :photo
    %br/
    = f.file_field :photo
  .actions
    = f.submit
 
 Now, update method in post_attachment_controller.rb

 def update
    respond_to do |format|
      if @post_attachment.update(post_attachment_params)
        format.html { redirect_to @post_attachment.post, notice: 'Post attachment was successfully updated.' }
      end
    end
  end


For Complete Source code click here