Rails 3.1 + Paperclip + jQuery fileupload
我一直在寻找一种方法来使用Paperclip和jQuery fileupload设置Ruby on Rails 3.1。 看一下jQuery fileupload页面上的教程,我得到了系统设置,但我找不到一种方法来使回形针处理上传的文件。
这就是我所拥有的(简而言之):
# model has_attached_file :photo ... # view = form_for @user, :html => {:multipart => true} do |f| f.file_field :photo, :multiple => true f.submit # controller def create @user = User.new params[:user] if @user.save render :json => [...] end
如果我检查提交的数据,我将获得params [:user]和params [:user] [:photo]中的所有用户属性,即ActionDispatch :: Http :: UploadedFile。 调用@ user.save时,不会处理或保存图像。
一个线索,教程或解决方案将非常感谢!
在解决了这个问题一段时间后,我发现问题出现在:multipart => true
添加到f.file_field
因为表单字段名称从user[photo]
更改为user[photo][]
。
使用单独的页面附加照片
我想有一个单独的页面用于将多个文件上载到记录(另一个用于编辑用户的属性)。 这在我看来是一个临时解决方案,但它的工作原理。 而不是f.form_field :photo, :multipart => true
我在视图中使用了form_field_tag 'user[photo]', :multiple => true
。
我的代码如下所示:
## app/model/user.rb has_attached_file :photo def to_fileupload_json { "name" => photo_file_name, "size" => photo_file_size, ... } end ## app/views/photos/new.html.haml = form_for @user, :url => users_path, :html => { :multipart => true } do |f| #fileupload = file_field_tag 'user[photo]', :multiple => true = f.submit = javascript_include_tag "jquery.fileupload.js" # require all other JS files needed for the plugin (jQuery, jQuery UI, ...) = stylesheet_link_tag "jquery.fileupload-ui.css" = render :partial => "jquery_file_templates" # partial with jQuery templates for responses :javascript $(function () { uploader = $('#fileupload').fileupload() } ## app/controllers/users_controller.rb def create @user = User.create params[:user] end
如果有其他人知道更好的方法(正确的方法),请告诉我们!
使用fields_for
根据应用程序的结构,您可以考虑使用fields_for
。
在这种情况下,你必须:
- 将
accepts_nested_attributes_for :photos
添加到您的(用户)模型 - 向您的(用户)模型添加方法
photos_attribues=(attributes)
并在那里处理记录创建 - 在User的新方法中为照片构建记录3
3.times { @user.photos.build }
例:
def photos_attribues=(attributes) attributes.each do |key, value| photo = Photo.create :photo => value, ... end end
免责声明:上面的代码已经过简化/重写,以便于理解。 我可能在删除不需要的东西时犯了错误。 而且 – 我不确定这是解决这个问题的正确方法。 建议和改进非常受欢迎!
如果在file_field
上显式设置名称:
f.file_field :photo, multiple: true, name: 'user[photo]'
Rails将生成user[photo]
而不是user[photo][]
。