我只想把我的答案在這裏,以及石的。我花了將近兩天的時間來完成這項工作(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