【发布时间】:2011-01-10 05:42:47
【问题描述】:
我正在尝试在嵌套表单中的文件字段上使用 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
观点:
<%= 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">
这似乎不对,因为我认为我想直接在对象上设置文件名,但我不确定这一点。当我尝试使用此字段上传时,传入的参数如下所示:
"album"=>{"name"=>"2011-01-09", "images"=>["IMG_0052.JPG", "IMG_0053.JPG", "IMG_0054.JPG", "IMG_0055.JPG"]}
但是,我收到以下错误:
ActiveRecord::AssociationTypeMismatch (Image(#2157004660) expected, got String(#2151988680)):
好的,该错误可能是由于它刚刚收到文件名而不是图像对象。因此,我改为使用文件字段:
<%= f.input :images, :as => :file, :input_html => {:multiple => true, :name => 'album[images][][filename]'} %>
Formtastic 为其生成:
<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 中设置这种多文件输入文件映射呢?
谢谢。
【问题讨论】:
-
投了反对票,因为您从未对以下答案提供任何反馈,并且如果您已经/尚未解决问题,也永远不会回来更新您的问题。
标签: html ruby-on-rails-3 nested-forms formtastic