5

Tôi đang thực hiện cập nhật ảnh async sử dụng xương sống & 'kẹp giấy' viên ngọc đường ray:Backbone + Rails 'Kẹp giấy' Async ơn

Câu hỏi:

  1. Tôi có cần phải sử dụng jQuery tải lên (hoặc lib tương đương)?
  2. Nếu có, tôi có chỉ cần ghi đè lên photocollection.sync để gọi thư viện không?

Item.rb

class Item < ActiveRecord::Base 
    has_many: photos 
    ... 

Photo.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() 

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> 
... 

Gợi ý để cải thiện thiết kế tổng thể được hoan nghênh

Trả lời

2

tôi đã kết thúc chọn cho sự đơn giản hỗ trợ & qua trình duyệt đã được upload xong iframe. Thực hiện thực sự là khá tầm thường:

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> 

Lưu ý việc bổ sung các CSRF Token. Nếu không có nó, yêu cầu sẽ thất bại & đã xóa phiên của bạn.

Các vấn đề liên quan