使用回形针的嵌套表格

时间:2011-05-01 20:06:15

标签: ruby-on-rails ruby ruby-on-rails-3 paperclip

我有一个名为posts的模型,它有很多附件。

附件模型使用回形针。

我创建了一个独立的模型来创建附件,工作得很好,这是这里指示的视图(https://github.com/thoughtbot/paperclip):

<% form_for :attachment, @attachment, :url => @attachment, :html => { :multipart => true } do |form| %>
  <%= form.file_field :pclip %>

  <%= form.submit %>

<% end %>

帖子中的嵌套表单如下所示:

<% @attachment = @posts.attachments.build %>
<%= form_for(@posts) do |f| %>
  <% if @posts.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@posts.errors.count, "error") %> prohibited this post from being saved:</h2>

      <ul>
      <% @posts.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :description %><br />
    <%= f.text_area :description %>
  </div>
  <div class="field">
    <%= f.fields_for :attachments, @attachment, :url => @attachment, :html => { :multipart => true } do |at_form| %>

      <%= at_form.file_field :pclip %>

    <% end %>
  </div>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

创建附件记录,但其为空。该文件未上传。同时,该帖子已成功创建......

有什么想法吗?

1 个答案:

答案 0 :(得分:9)

您在表单定义中缺少:multipart选项:

<% @attachment = @post.attachments.build %>
<%= form_for @post, :html => { :multipart => true } do |f| %>
  <% if @post.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>

      <ul>
      <% @post.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :description %><br />
    <%= f.text_area :description %>
  </div>
  <div class="field">
    <%= f.fields_for :attachments, @attachment do |at_form| %>

      <%= at_form.file_field :pclip %>

    <% end %>
  </div>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

另外,你的@posts变量应该是@post(单个ActiveRecord实例而不是ActiveRecord实例数组)。