ruby-on-rails - Backbone + Rails 'Paperclip' 异步上传

标签 ruby-on-rails backbone.js coffeescript paperclip ajax-upload

我正在使用主干和 rails 'paperclip' gem 实现异步照片上传:

问题:

  • 我需要使用 jQuery 上传(或等效的库)吗?
  • 如果是这样,我是否只需覆盖 photocollection.sync 来调用库?

  • 项目.rb
    class Item < ActiveRecord::Base
       has_many: photos
       ...
    

    照片.rb
    class Photo < ActiveRecord::Base
    
      attr_accessible :photo
      belongs_to :item
    
      has_attached_file :photo
    ...
    

    ItemView.js.coffee
    class MySite.Views.Items.Edit extends Backbone.View
    
      template: JST['items/edit']
    
      initialize: ->
        @modelBinder = new Backbone.ModelBinder
        @model.on('change', @render(), this)
    
      events: ->
        'submit #edit_item_form' : 'save_item'
    
      render: ->
        $(@el).html @template( item: @model )
    
        @new_photo = @model.new_photo()
    
        @modelBinder.bind @model, $("#item_fields")
        @modelBinder.bind @new_photo, $("#photo_fields")
        @
    
      save_item: (e) ->
        e.preventDefault()
        @model.save()
        @new_photo.save()
    

    编辑.jst.eco
    <form id="edit_item_form" accept-charset="UTF-8" data-remote="true" enctype="multipart/form-data">
    <div id="item_fields"> .... </div>
    <div id="photo_fields">
       <input type="file" id="upload_photo" name="photo[photo]" />
    </div>
    ...
    

    欢迎提出整体设计改进的建议

    最佳答案

    我最终选择了 iframe 上传的简单性和跨浏览器支持。实现实际上非常简单:

    MyView.js.coffee:

      events: ->
        'change #upload_photos' : 'upload_photo'
    
      upload_photo: (e) ->
        upload_frame = $('#add_photo_form')
        upload_frame.prop 'target', 'upload_frame'
        upload_frame.submit()
    

    MyTemplate.jst.eco:
    <form id="add_photo_form" method="POST" action="/api/v1/photos" enctype="multipart/form-data">
      <div id="photo_fields">
          <input type="file" id="upload_photos" name="photo[photo]" multiple>
          <input type="hidden" name="authenticity_token" value="<%= $("meta[name='csrf-token']").attr("content") %>">
      </div>
    </form>
    <iframe id='upload_frame' name='upload_frame' src=''></iframe>
    

    请注意 CSRF token 的添加。没有它,请求将失败并清除您的 session 。

    关于ruby-on-rails - Backbone + Rails 'Paperclip' 异步上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13100393/

    相关文章:

    ruby-on-rails - 将一个或两个参数传递给Rake任务

    选择文件后的Javascript代码

    javascript - 主干 View 接收常规对象而不是模型

    backbone.js - 子类化 Backbone.View

    javascript - CoffeeScript:使用对象作为参数

    javascript - 无法使用 Backbone.Marionette 访问模型属性

    ruby-on-rails - 为 MultiJson :Module for jbuilder 获取未定义的方法 `dump'

    ruby-on-rails - yaml 格式是否有命名约定?

    mysql - 在连接表上使用 where

    javascript - 'options || (options = {})' 是做什么的?