2015-01-11 1 views
0

Dropzone Js를 내 레일 앱에서 클립과 결합하여 jquery를 정렬 할 수있었습니다.RoR : jQuery와 정렬 가능한 Dropzone.js

내 목적은 다음과 같습니다

  1. 내가 (일종의)의 순서를 변경하면 업로드 성공의 DB에
  2. 업데이트 dB의 각 이미지의 위치를 ​​모든 이미지의 위치를 ​​저장 할 수 있도록 이미지들.

내 업로드 모델이 있습니다 이미지 : 위치 을 내 노선 수집 {포스트 "종류"}

내 컨트롤러 코드가 있습니다

class UploadsController < ApplicationController 

    def new 
    @upload = Upload.new 
    end 

    def upload_list 
    @uploads = Upload.all.select(:id, :image_file_name, :image_file_size).order("position") 

    respond_to do |format| 
     format.json {render json: @uploads.to_json(methods: [:path])} 
    end 
    end 

    def create 
    @upload = Upload.create(upload_params) 
    @upload.position = params[:upload][:position] 

    if @upload.save 
     render json: { message: "success", fileID: @upload.id }, :status => 200 
    else 
     render json: { error: @upload.errors.full_messages.join(',')}, :status => 400 
    end 
    end 

    def sort 
    //params[:upload] gives undefined method for nil error 
    Upload.all.each_with_index do |id, index| 
     Upload.where(id: id).update_all({position: index+1}) 
    end 
    render nothing: true 
    end 

    def destroy 
    @upload = Upload.find(params[:id]) 
    if @upload.destroy 
     render json: { message: "File deleted from server" } 
    else 
     render json: { message: @upload.errors.full_messages.join(',') } 
    end 
    end 

    private 
    def upload_params 
     params.require(:upload).permit(:image, :position) 
    end 
end 

upload.rb :

class Upload < ActiveRecord::Base 

    has_attached_file :image, :styles => { :medium => "300x300>",:thumb => "100x100>" } 

    validates_attachment :image, 
        :presence => true, 
        :content_type => { :content_type => /\Aimage\/.*\Z/ }, 
        :size => { :less_than => 1.megabyte } 

    def path 
    image.url 
    end 

    def as_json(options = { }) 
    h = super(options) 
    h["name"] = h.delete "image_file_name" 
    h["size"] = h.delete "image_file_size" 
    h 
    end 

end 

new.html.erb :

,463,210

마지막 uploads.js는 :

$(document).ready(function(){ 

    Dropzone.autoDiscover = false; 

    $("#new_upload").dropzone({ 
    maxFilesize: 1, 
    paramName: "upload[image]", 
    addRemoveLinks: true, 
    dictRemoveFile: "Delete", 

    //to show existing images from db 
    init: function() { 
     var thisDropZone = this; 
     $.getJSON('upload_list', function(data) { 
     $.each(data, function(index, val) { 
      var mockFile = { name: val.name, size: val.size }; 
      thisDropZone.emit("addedfile", mockFile); 
      thisDropZone.emit("thumbnail", mockFile, val.path); 
      $(mockFile.previewTemplate).find('.dz-remove').attr('id', val.id); 

      // adding id attribute for serialize 
      $(".dz-preview:last-child").attr('id', "image_" + val.id); 
     }); 
     }); 
    }, 

    success: function(file, response){ 
     $(file.previewTemplate).find('.dz-remove').attr('id', response.fileID); 
     $(file.previewElement).addClass("dz-success"); 

     var order = $('.dropzone').sortable('serialize'); 
     $.ajax({ 
     type: 'POST', 
     url: '/uploads/sort', 
     data: order, 
     success: function(data){ 
      console.log(data); 
     }   
     }); 
    }, 

    removedfile: function(file){ 
     var id = $(file.previewTemplate).find('.dz-remove').attr('id'); 
     file.previewElement.remove(); 

     $.ajax({ 
     type: 'DELETE', 
     url: '/uploads/' + id, 
     success: function(data){ 
      console.log(data.message); 
     } 
     }); 

     var order = $('.dropzone').sortable('serialize'); 
     $.ajax({ 
     type: 'POST', 
     url: '/uploads/sort', 
     data: order, 
     success: function(data){ 
      console.log(data); 
     }   
     }); 
    } 
    }); 

//this function is for sorting + updating positions of old images loaded by the init function. 
    $(function() { 
    $(".dropzone").sortable({ 
     items:'.dz-preview', 
     cursor: 'move', 
     opacity: 0.5, 
     containment: '.dropzone', 
     distance: 20, 
     update: function(event, ui) { 
     var order = $('.dropzone').sortable('serialize'); 
     $.ajax({ 
      type: 'POST', 
      url: '/uploads/sort', 
      data: order, 
      success: function(data){ 
      console.log(data); 
      }   
     }); 
     } 
    }); 
    $(".dropzone").disableSelection(); 
    }); 
}); 

나는 내가해야 할 청소를 많이 가지고 알고 있지만 내가 처음 일을 얻기 위해 노력하고있어.

serialize가 작동하려면 dropzone의 각 이미지의 .dz-preview에서 "_"앞에 ID가 필요하다는 것을 알고 있습니다. 그러나 성공 함수 아약스 게시물 id 속성을 적용하지 않고 잘 작동하고 그래서 3 이미지를 업로드 할 때 db 위치를 각각 1, 2 및 3, 또한 removedfile 함수를 작동합니다, 만약 내가 두 번째 이미지를 제거, image1은 위치 "1"을 가져오고 image3은 컨트롤러의 정렬 방법 덕분에 position 속성이 2로 업데이트됩니다.

내가 시도한 것은 id 속성을 .dz 미리보기에 추가하고 init 함수를 테스트하고 다시 정렬을 시도하도록 페이지를 새로 고치기 위해 init 함수에 행을 추가하는 것과 같습니다. 이다

Started POST "/uploads/sort" for 127.0.0.1 at 2015-01-12 12:47:39 +0200 
Processing by UploadsController#sort as */* 
Parameters: {"image"=>["318", "320", "319"]} 
Upload Load (2.7ms) SELECT "uploads".* FROM "uploads" 
SQL (5.4ms) UPDATE "uploads" SET "position" = 1 WHERE "uploads"."id" = 318 
SQL (14.7ms) UPDATE "uploads" SET "position" = 2 WHERE "uploads"."id" = 319 
SQL (1.8ms) UPDATE "uploads" SET "position" = 3 WHERE "uploads"."id" = 320 
Rendered text template (0.1ms) 
Completed 200 OK in 54ms (Views: 2.0ms | ActiveRecord: 29.6ms) 

통지 파라미터들의 순서는 그렇게 화상 "318"1 위치를 취한다 "320"위치 (2)를 가지고 "319"위치 3해야하지만 같이 새로운 순서는해야 업데이트에서 무시되었습니다 ...

내가 누락 된 아이디어가 있습니까? 그것은 정렬 메서드 또는 .sortable 함수입니까?

감사

답변

1

업데이트 코드를 다음 사용하여 정렬 작업입니다.

def sort 
    images = Upload.where(id: params[:image]) 
    images.each do |image| 
     if position = params[:image].index(image.id.to_s) 
     image.update_attribute(:position, position + 1) unless image.position == position 
     end 
    end 
    render nothing: true 
    end 
+0

은 의미가 있지만, 이제는 메소드가 어떤 ID도 얻지 못하고있는 것 같습니다. 매개 변수 : { "image"=> [ "319", "320", "318"] 로드 업로드 (0.4ms) SELECT "업로드". * FROM "업로드"WHERE "업로드". "id"IS NULL – Shalaby

+1

업데이트 답변, params [: image] 대신 params [: upload] –

+0

if 문에 여분의 "="를 추가했지만 위치가 정의되어 있지 않은 것으로 나타났습니다. image.position과 if 문 내에서의 위치를 ​​비교하여 ur가 그렇게 생각할 것입니다 ... 그래서 어떤 위치를 정의해야합니까? – Shalaby

관련 문제