我正在尝试使用Carrierwave Cloudinary direct uploads使用Rails应用程序,accepts_nested_attributes_for
使用帖子提交一个或多个图像。它工作正常,直到我尝试动态添加更多上传字段。由于某些原因,在选择图像/文件时,动态添加的内容不会开始上传。
详细...
模型摘要:
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>
的Gemfile:
gem 'carrierwave'
gem 'cloudinary'
的application.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 partial:
<div class="upload">
<%= f.label :file, "Image" %>
<%= f.hidden_field(:file_cache) %>
<%= f.cl_image_upload(:file) %>
</div>
所以,这一切都很有效。图像直接上传到Cloudinary并使用帖子表单正确保存。但是,我不希望用户被限制为每个帖子只有三张图片,所以我改编了Railscast 196的代码,用JavaScript添加其他上传字段。
CoffeeScript:
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()
新添加字段链接: (使用'uploads'类放置在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)。
但是,在选择文件时,新生成的上载字段不会启动上载。什么都没发生。任何人都有任何想法?
答案 0 :(得分:4)
您需要使用$(selector).cloudinary_fileupload();
初始化新创建的输入字段