R
R
Risent Veber2015-09-05 17:10:23
JavaScript
Risent Veber, 2015-09-05 17:10:23

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

As an Uploader, a standard one generated using Carrierwave is used.
class Attachment < ActiveRecord::Base
  belongs_to :attachable, polymorphic: true
  mount_uploader :file, FileUploader
end


The attachments themselves are created using AJAX, which, using the
appropriate controller action, creates an Attachement and receives the id and url of the .
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

This is how the JSON template for the response looks like:
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)


And so the very creation of Material
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


Please tell me, are there any ways to make this functionality better, say directly with the help of temporary files that will be deleted if the user does not create the material to which they were supposed to be attached?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
CapeRatel, 2015-09-06
@CapeRatel

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 question

Ask a Question

731 491 924 answers to any question