HTML5多文件上载字段如何映射到Rails 3中的嵌套模型? [英] How does the HTML5 multiple file upload field map to a nested model in Rails 3?

查看:120
本文介绍了HTML5多文件上载字段如何映射到Rails 3中的嵌套模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以嵌套形式在文件字段上使用HTML5 multiple属性。

I'm trying to use the HTML5 multiple attribute on a file field in a nested form.

模型如下:

class Album < ActiveRecord::Base

  has_many :album_images
  has_many :images, :through => :album_images

  accepts_nested_attributes_for :images

end

class Image < ActiveRecord::Base

  has_many :album_images
  has_many :albums, :through => :album_images

  mount_uploader :filename, ImageUploader

  validates_presence_of :filename

end

视图:

  <%= semantic_form_for @album, :url => upload_path do |f| %>
    <%= f.inputs do %>
      <%= f.input :name, :label => 'Album title' %>
    <% end %>

    <%= f.input :images, :as => :file, :input_html => {:multiple => true} %>

    <%= f.buttons do %>
      <%= f.commit_button 'Upload' %>
    <% end %>
  <% end %>

当我用于文件字段时:

<%= f.input :images, :as => :file, :input_html => {:multiple => true} %>

我得到:

<input id="album_images" multiple="multiple" name="album[images][]" type="file">

这似乎不对,因为我想我想要直接在对象上设置文件名,但我不确定。当我尝试使用此字段上传时,传入的参数类似于:

Which doesn't doesn't seem right since I think I want to set the filename on the object directly, but I'm not sure about this. When I try to upload with this field, the incoming params look like:

 "album"=>{"name"=>"2011-01-09", "images"=>["IMG_0052.JPG", "IMG_0053.JPG", "IMG_0054.JPG", "IMG_0055.JPG"]}

但是,我收到以下错误:

However, I get the following error:

ActiveRecord::AssociationTypeMismatch (Image(#2157004660) expected, got String(#2151988680)):

好的,这个错误可能是由于它刚刚收到文件名而不是图像对象。所以相反,我用于文件字段:

OK, that error is probably due to the fact that it just received a filename and not an image object. So instead, I use for the file field:

<%= f.input :images, :as => :file, :input_html => {:multiple => true, :name => 'album[images][][filename]'} %>

<input id="album_images" multiple="multiple" name="album[images][][filename]" type="file">

传入的参数看起来像:

"album"=>{"name"=>"2011-01-09", "images"=>[{"filename"=>"IMG_0052.JPG"}, {"filename"=>"IMG_0053.JPG"}, {"filename"=>"IMG_0055.JPG"}]}

然后我收到此错误:

Image(#2153868680) expected, got ActiveSupport::HashWithIndifferentAccess(#2158892780)

那么如何设置这个多文件输入字段映射Rails?

So how does one go about setting up this multiple file input filed mapping in Rails?

谢谢。

推荐答案

你需要包含:html => {:multipart =>在您的 form_for (或在您的情况下 semantic_form_for )中调用true} 以便< form> 标记设置为支持文件上传。

You need to include :html => { :multipart => true } in your form_for (or in your case semantic_form_for) call so that your <form> tag is set to support file uploads.

然后还原为 f.input 的原始语法,你应该是正确的。

Then revert back to your original syntax for f.input and you should be right then.

这篇关于HTML5多文件上载字段如何映射到Rails 3中的嵌套模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆