HTML5多文件上载字段如何映射到Rails 3中的嵌套模型?

cot*_*axi 14 html5 nested-forms formtastic ruby-on-rails-3

我试图在嵌套表单中的文件字段上使用HTML5多重属性.

模型如下:

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
Run Code Online (Sandbox Code Playgroud)

风景:

  <%= 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 %>
Run Code Online (Sandbox Code Playgroud)

当我用于文件字段时:

<%= f.input :images, :as => :file, :input_html => {:multiple => true} %>
Run Code Online (Sandbox Code Playgroud)

我明白了:

<input id="album_images" multiple="multiple" name="album[images][]" type="file">
Run Code Online (Sandbox Code Playgroud)

这似乎不对,因为我想我想直接在对象上设置文件名,但我不确定这一点.当我尝试使用此字段上传时,传入的参数看起来像:

 "album"=>{"name"=>"2011-01-09", "images"=>["IMG_0052.JPG", "IMG_0053.JPG", "IMG_0054.JPG", "IMG_0055.JPG"]}
Run Code Online (Sandbox Code Playgroud)

但是,我收到以下错误:

ActiveRecord::AssociationTypeMismatch (Image(#2157004660) expected, got String(#2151988680)):
Run Code Online (Sandbox Code Playgroud)

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

<%= f.input :images, :as => :file, :input_html => {:multiple => true, :name => 'album[images][][filename]'} %>
Run Code Online (Sandbox Code Playgroud)

Formtastic产生的:

<input id="album_images" multiple="multiple" name="album[images][][filename]" type="file">
Run Code Online (Sandbox Code Playgroud)

传入的参数看起来像:

"album"=>{"name"=>"2011-01-09", "images"=>[{"filename"=>"IMG_0052.JPG"}, {"filename"=>"IMG_0053.JPG"}, {"filename"=>"IMG_0055.JPG"}]}
Run Code Online (Sandbox Code Playgroud)

但后来我得到了这个错误:

Image(#2153868680) expected, got ActiveSupport::HashWithIndifferentAccess(#2158892780)
Run Code Online (Sandbox Code Playgroud)

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

谢谢.

sma*_*thy 2

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

然后恢复到原来的语法,那么f.input你应该是对的。