Backbone + Rails'Paperclip'异步上传

pws*_*068 5 ruby-on-rails paperclip ajax-upload coffeescript backbone.js

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

问题:

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

item.rb的

class Item < ActiveRecord::Base
   has_many: photos
   ...
Run Code Online (Sandbox Code Playgroud)

Photo.rb

class Photo < ActiveRecord::Base

  attr_accessible :photo
  belongs_to :item

  has_attached_file :photo
...
Run Code Online (Sandbox Code Playgroud)

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()
Run Code Online (Sandbox Code Playgroud)

Edit.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>
...
Run Code Online (Sandbox Code Playgroud)

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

pws*_*068 2

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

MyView.js.咖啡:

  events: ->
    'change #upload_photos' : 'upload_photo'

  upload_photo: (e) ->
    upload_frame = $('#add_photo_form')
    upload_frame.prop 'target', 'upload_frame'
    upload_frame.submit()
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

请注意添加了 CSRF 令牌。如果没有它,请求将失败并清除您的会话。