i am using carrierwave for multiple file uploads.
My post model:
class Post < ActiveRecord::Base
has_many :post_attachments
accepts_nested_attributes_for :post_attachments
end
post_attachment.rb:
class PostAttachment < ActiveRecord::Base
mount_uploader :avatar, AvatarUploader
belongs_to :post
end
posts_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]['avatar'].each do |a|
@post_attachment = @post.post_attachments.create!(:avatar => a, :post_id => @post.id)
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, :avatar])
end
and my posts/_form is:
<%= form_for(@post, :html => { :multipart => true }) do |f| %>
<div class="field">
<%= f.label :title %><br>
<%= f.text_field :title %>
</div>
<%= f.fields_for :post_attachments do |p| %>
<div class="field">
<%= p.label :avatar %><br>
<%= p.file_field :avatar, :multiple => true, name: "post_attachments[avatar][]" %>
</div>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Actually the above code is referred from Rails 4 multiple image or file upload using carrierwave.
Initially i have done single file upload using http://richonrails.com/articles/allowing-file-uploads-with-carrierwave where I used to download the file. For this I used to write a method in my controller as:
def download
respond_to do |format|
format.html {
if params[:post_id].nil?
redirect_to :back
else
begin
post = Post.find(params[:post_id])
attachment_file = File.join('public', post.attachment.url)
if File.exists?(attachment_file)
send_file attachment_file, :disposition => 'attachment'
else
redirect_to :back
end
rescue Exception => error
redirect_to :back
end
end
}
end
end
and in posts/index.html.erb:
<% @posts.each do |post| %>
<tr>
<td align="center">
<%= link_to image_tag("download.png"), download_post_path(post.id) %>
</td>
</tr>
<% end %>
attachment_uploader.rb:
class AttachmentUploader < CarrierWave::Uploader::Base
storage :file
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
end
How can I download multiple files for a post_id as a zip with my code?