1

我正在尝试使用 Carrierwave 在 Rails 应用程序上使用Cloudinary 直接上传accepts_nested_attributes_for,并通过帖子提交一个或多个图像。在我尝试动态添加更多上传字段之前,它工作正常。For some reason those added dynamically won't start uploading when an image/file is chosen.

细节...

型号总结:

class Post < ActiveRecord::Base
  has_many :images
  accepts_nested_attributes_for :images,
    reject_if: proc { |a| a['file'].blank? && a['file_cache'].blank? }
  attr_accessible :images_attributes
end

class Image < ActiveRecord::Base
  belongs_to :post
  attr_accessible :file, :file_cache
  mount_uploader :file, ImageUploader
end

控制器摘要:( 一个起点,允许我在一个帖子中最多包含三个图像)

class PostsController < ApplicationController
  def new
    @post = Post.new
    3.times { @post.images.build }
  end
end

头:

<!DOCTYPE html>
<html>
<head>
  ...
  <%= javascript_include_tag "application" %>
  <%= cloudinary_js_config %>
</head>

宝石文件:

gem 'carrierwave'
gem 'cloudinary'

应用程序.js:

//= require jquery
//= require jquery_ujs
//= require cloudinary

上传者:

require 'carrierwave/processing/mime_types'

class ImageUploader < CarrierWave::Uploader::Base
  include Cloudinary::CarrierWave
end

邮寄表格:

<%= form_for @post, :html => { :class => "form" } do |f| %>
  ...
  <div class="uploads">
    <div class="field">
      <%= f.fields_for :images do |builder| %>
        <%= render "image_fields", f: builder %>
      <% end %>
    </div>
  </div>
  ...
  <%= f.submit "Save Post" %>
<% end %>

image_fields.html.erb 部分:

<div class="upload">
  <%= f.label :file, "Image" %>
  <%= f.hidden_field(:file_cache) %>
  <%= f.cl_image_upload(:file) %>
</div>

所以,这一切都很好。图像直接上传到 Cloudinary,并与帖子表单一起正确保存。但是,我不希望用户被限制为每个帖子只有三张图片,所以我改编了Railscast 196的代码以使用 JavaScript 添加额外的上传字段。

咖啡脚本:

jQuery ->
  $('form').on 'click', '.add_fields', (event) ->
    $list = $('.uploads')
    $lis = $list.find('.upload')
    newIndex = $lis.length
    regexp = new RegExp($(this).data('id'), 'g')
    $(this).before($(this).data('fields').replace(regexp, newIndex))
    event.preventDefault()

一个新的添加字段链接:( 放置在 fields_for 下方和带有“上传”类的 div 内)

<%= link_to_add_fields "Add Image", f, :images %>

一个新的图像助手:

def link_to_add_fields(name, f, association)
  new_object = f.object.send(association).klass.new

  id = new_object.object_id

  fields = f.fields_for(association, new_object, child_index: id) do |builder|
    render(association.to_s.singularize + "_fields", f: builder)
  end

  link_to(name, '#', class: "add_fields", data: {id: id, fields: fields.gsub("\n", "")})
end

这似乎在三个最初创建的上传字段继续正常工作(即立即上传)的意义上起作用,并且单击“添加图像”链接确实会生成一个具有连续 ID 的新上传字段(除了 ID 之外它们是相同的)。

但是,选择文件时,新生成的上传字段不会启动上传。什么都没发生。有人知道为什么吗?

4

1 回答 1

4

您需要使用 $(selector).cloudinary_fileupload(); 初始化新创建的输入字段;

于 2013-12-11T07:30:48.400 回答