Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested form using paperclip

I have a model called posts, and it has many attachments.

The attachments model is using paperclip.

I made a standalone model for creating attachments which works just fine, this is the view as instructed here (https://github.com/thoughtbot/paperclip):

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

  <%= form.submit %>

<% end %>

The nested form in posts looks like this:

<% @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 %>

An attachment record is created, but its empty. The file is not uploaded. The post meanwhile, is successfully created...

Any ideas?

like image 289
Elliot Avatar asked May 01 '11 20:05

Elliot


1 Answers

You are missing the :multipart option in your form definition:

<% @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 %>

Also, your @posts variable should really be @post (single ActiveRecord instance as opposed to an array of ActiveRecord instances).

like image 93
mbreining Avatar answered Sep 22 '22 00:09

mbreining