使用 Rails 3.2 和 Paperclip 使用 HTML5 一次上传多个文件(照片)multipart
。这是我的表格:
# shops/_form.html.erb
<%= form_for @shop, :url => { :action => action, :type => type }, :html => { :multipart => true } do |f| %>
<%= f.text_field :name %>
<%= f.file_field :shop_photos_data, :multiple => true, :name => "shop[photos_attributes][][data]" %>
<% end %>
它工作并在更新/创建时产生以下结果:
{"utf8"=>"✓",
"authenticity_token"=>"9jXvIwcllct7UyUfo6cvhEucQf2u3SY50SuaCLtFO4c=",
"shop"=>{
"name"=>"First shop",
"photos_attributes"=>{"0"=>{
"image"=>[
#<ActionDispatch::Http::UploadedFile:0x00000104b78978
@original_filename="first_test_image.jpg",
@content_type="image/jpeg",
@headers="Content-Disposition: form-data; name=\"gallery[photos_attributes][0][image][]\"; filename=\"first_test_image.jpg\"\r\nContent-Type: image/jpeg\r\n",
@tempfile=#<File:/var/folders/bQ/bQYZC2ukFZCvbKzEDGRtJE+++TI/-Tmp-/RackMultipart20110622-4459-vz78ee>>,
#<ActionDispatch::Http::UploadedFile:0x00000104b78950
@original_filename="second_test_image.jpg",
@content_type="image/jpeg",
@headers="Content-Disposition: form-data; name=\"gallery[photos_attributes][0][image][]\"; filename=\"second_test_image.jpg\"\r\nContent-Type: image/jpeg\r\n",
@tempfile=#<File:/var/folders/bQ/bQYZC2ukFZCvbKzEDGRtJE+++TI/-Tmp-/RackMultipart20110622-4459-1jzhhyg>>
]
}
}
}, "commit"=>"Save", "action"=>"create", "controller"=>"shops"}
它有效,它进入shops_controller.rb
,但不进入photos_controller.rb
。
这是我的代码的其他部分:
# photo.rb
class Photo < ActiveRecord::Base
belongs_to :attachable, :polymorphic => true, :counter_cache => true
belongs_to :user, :counter_cache => true
attr_accessible :data, :attachable_id, :attachable_type, :user_id
end
# shop.rb
class Shop < ActiveRecord::Base
attr_protected :photos_count
has_many :photos, :as => :attachable, :dependent => :destroy
accepts_nested_attributes_for :photos, :allow_destroy => true
end
# photos_controller.rb
class PhotosController < ApplicationController
end
# shops_controller.rb
class ShopsController < ApplicationController
before_filter :require_user, :only => [:new, :edit, :update, :create]
...
def update
@shop = Shop.find(params[:id])
if @shop.update_attributes(params[:shop])
flash[:notice] = 'Successfully updated.'
redirect_to shop_path(@shop)
else
render :action => :edit
end
end
end
我的模型中有一个user_id
字段Photo
。目前,user_id
没有保存在每个新Photo
记录中。我可以在文件上传数组中包含什么shops_controller.rb
?user_id
我不想在表单中这样做,因为它暴露了安全性。
谢谢。