Answer the question
In order to leave comments, you need to log in
How to make a backend for a form that provides the ability to bind multiple files to the created object with their preview?
Here's what I came up with myself - but I think there are more elegant options:
Let's say there is some Material (well, not a beaten Post), to which files are attached (Attachment)
class Material < ActiveRecord::Base
has_many :attachments, as: :attachable, dependent: :destroy
end
class Attachment < ActiveRecord::Base
belongs_to :attachable, polymorphic: true
mount_uploader :file, FileUploader
end
class AttachmentsController < ApplicationController
def create
@a = Attachment.new(file: params[:file])
if @a.save
render 'create.json', layout: false
else
render json: {error: 'ERROR'}
end
end
end
elem_id = "attachment" + @a.id.to_s
json.id @a.id
json.link @a.file.url
json.remove_link (link_to '×', attachment_path(@a),
method: :delete, remote: true, id: elem_id, class: 'X18')
json.type @a.type
json.name truncate(@a.file.file.filename, length: 20)
class MaterialsController < ApplicationController
def create
@material = Material.new do |m|
m.description = params[:description]
m.user = current_user
m.subject_id = params[:tag]
end
@material.save!
@material.classrooms << Classroom.find(params[:classroom_id])
@files = params[:attached_files]
@files = @files.to_s.squish.split(" ")
Attachment.find(@files).each do |f|
f.attachable = @material
f.save!
end
end
end
Answer the question
In order to leave comments, you need to log in
Uploaders:
https://github.com/tors/jquery-fileupload-rails
https://github.com/ncuesta/dropzonejs-rails
To make photo preview work on upload, you can just use js and html5. You need to google something like this:
If you want a solution so that the files still load, then it's better to use whenever and clean the pictures without linking, as FanKiLL advised you
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question