Rails 4 : Multiple file upload with carrierwave, nested form and jquery file upload - iqbal hasnan http://reka.co https://u.osu.edu/hasnan.1/2014/03/30/rails-4-multiple-file-upload-with-carrierwave-nested-form-and-jquery-file-upload/
class PhotosController < ApplicationController
# truncated for brevity.
def create
params[:images].each{ |image|
@photo = Photo.create(image: image)
if @photo.save
respond_to do |format|
format.html { render json: @photo.to_jq_upload, content_type: 'text/html', layout: false }
format.json { render json: @photo.to_jq_upload }
end
else
render json: { error: @photo.errors.full_messages }, status: 304
end
}
end
end
class Photo < ActiveRecord::Base
#photo belongs to album
belongs_to :album
#validations
validates :album, presence: true
# Photo uploader using carrierwave
mount_uploader :image, PhotoUploader
def to_jq_upload
{
"url" => image.medium.url,
"delete_url" => id,
"picture_id" => id,
"delete_type" => "DELETE"
}.to_json
end
end
$(function(){
var ids = [];
$('#album_upload').fileupload({
done: function (e, data) {
ids.push(data.result.picture_id);
$('#photos_ids').val(ids);
}
});
});
class AlbumsController < ApplicationController
# truncated for brevity.
def create
@album = current_user.albums.build(album_params)
@album.photos << Photo.find(params[:photos].split(","))
authorize @album
if @album.save
flash[:notice] = "Your album has been created."
redirect_to @album
else
flash[:alert] = "Something went wrong."
render :new
end
end
def album_params
params.require(:album).permit(:title, :description, :photos_attributes => [:album_id, :image])
end
end
class Album < ActiveRecord::Base
# belongs to user model
belongs_to :user
# Album has many photos
has_many :photos, :inverse_of => :album, :dependent => :destroy
# enable nested attributes for photos through album class
accepts_nested_attributes_for :photos, allow_destroy: true
end
<input id="photos_ids" name="photos" type="hidden" value="">
<input data-url="/photos" id="album_upload" multiple="multiple" name="images[]" type="file" ></input>
This gist is the update of this post https://u.osu.edu/hasnan.1/2014/03/30/rails-4-multiple-file-upload-with-carrierwave-nested-form-and-jquery-file-upload/
License MIT