【问题标题】:Nested form using paperclip使用回形针嵌套表单
【发布时间】:2011-05-01 20:06:15
【问题描述】:

我有一个模型叫做帖子,它有很多附件。

附件模型使用回形针。

我制作了一个独立的模型来创建附件,效果很好,这是此处指示的视图 (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 %>

创建了一个附件记录,但它是空的。文件未上传。同时,帖子创建成功...

有什么想法吗?

【问题讨论】:

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


    【解决方案1】:

    您在表单定义中缺少 :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 实例数组)。

    【讨论】:

    • +1 另外,我认为您不需要在 fields_for 块中使用它。
    • 很好,我错过了那个。我更新了代码 sn-p。还删除了不属于那里的 :url 选项(在 fields_for 级别)。
    猜你喜欢
    • 2016-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 2018-07-16
    • 1970-01-01
    • 2013-12-14
    相关资源
    最近更新 更多