我只想把我的答案在这里,以及石的。我花了将近两天的时间来完成这项工作(Stone是对的,这是一个PITA!),所以希望我的解决方案能够帮助某人。我做的只是一个不同于斯通的触觉。
我的应用程序有Features
(漫画,益智,文字列等)和FeatureAssets
(个人漫画面板/颜色的版本,质疑&应答文件特定字谜等)。由于FeatureAssets
仅与一个Feature
相关,因此我嵌套了这些模型(正如您在我的上传表单中看到的那样)。
对我来说,最大的问题就是意识到我params[:feature_asset]
正被发送到服务器实际上是我uploader'd file
对象的数组,而不是只是一个我,以利用工作。在迭代遍历每个文件并从中创建FeatureAsset之后,它会像魅力一样工作!
希望我会把它清楚地翻译出来。我宁愿提供太多信息,也不够。当你解释别人的代码时,一点额外的上下文不会受到伤害。
功能。RB
class Feature < ActiveRecord::Base
belongs_to :user
has_many :feature_assets
attr_accessible :name, :description, :user_id, :image
accepts_nested_attributes_for :feature_assets, :allow_destroy => true
validates :name, :presence => true
validates :user_id, :presence => true
mount_uploader :image, FeatureImageUploader
end
feature_asset.rb
belongs_to :user
belongs_to :feature
attr_accessible :user_id, :feature_id, :file, :file_cache
validates :user_id, :presence => true
validates :feature_id, :presence => true
validates :file, :presence => true
mount_uploader :file, FeatureAssetContentUploader
# grabs useful file attributes & sends them as JSON to the jQuery file uploader
def to_jq_upload
{
"file" => file,
"file_name" => 'asdf',
"url" => file.url,
"delete_url" => id,
"delete_type" => "DELETE"
}
end
feature_assets_controller.rb
def create
@feature = Feature.find(params[:feature_id])
params[:feature_asset]['file'].each do |f|
@feature_asset = FeatureAsset.create!(:file => f, :feature_id => @feature.id, :user_id => current_user.id)
end
redirect_to @feature
end
而且不是,它可能有助于多,但我feature_asset_uploader.rb如下。它相当精简。
class FeatureAssetContentUploader < CarrierWave::Uploader::Base
storage :file
end
功能_form.html.erb(类似石头的,但并不完全)
<%= form_for [@feature, @feature_asset], :html => { :multipart => true } do |f| %>
<div class="row" id="fileupload">
<div class=" fileupload-buttonbar">
<div class="progressbar fileupload-progressbar nofade"><div style="width:0%;"></div></div>
<span class="btn btn-primary fileinput-button">
<i class="icon-plus"></i>
<span><%= t('feature_assets.add_files') %>...</span>
<%= hidden_field_tag :feature_id, @feature.id %>
<%= hidden_field_tag :user_id, current_user.id %>
<%= f.file_field :file, :multiple => true %>
</span>
<button type="submit" class="btn btn-success">Start Upload</button>
<button type="reset" class="btn btn-warning">Cancel Upload</button>
<button type="button" class="btn btn-danger">Delete Files</button>
</div>
</div>
它没有错误处理或任何它应该有大乐事,但是这就是准系统版本的。
希望能帮助那里的人。随意问我,如果您有任何问题!
凯尔
嘿,我我有一个类似的问题,我似乎无法使用jQuery-File-Upload与nested_form gem。你能找到解决办法吗? – 2012-04-02 13:47:39
你要求AJAX上传专门,因为在用户仍然填写表格的其余部分的文件发送,是吗?你是否在处理图像或一般文件?而且,Attachment模型除了文件之外还有其他什么 - 任何验证等? – Andrew 2012-04-21 00:42:28