【问题标题】:How does the HTML5 multiple file upload field map to a nested model in Rails 3?HTML5 多文件上传字段如何映射到 Rails 3 中的嵌套模型?
【发布时间】: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


【解决方案1】:

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

然后恢复为 f.input 的原始语法,然后您应该是正确的。

【讨论】:

    猜你喜欢
    • 2012-03-10
    • 1970-01-01
    • 2011-07-28
    • 1970-01-01
    • 2011-06-01
    • 2021-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多