Victor Sprengel Victor Sprengel - 1 month ago 11
Ruby Question

Ask for attachment on form (Paperclip)

Foreword: I'm a REAL rails newbie. I'm developing my first web application with it and therefore even basic concepts are hard to understand for me.

Having said thay, my problem:

I'm planning to use Paperclip (and Paperclip only) to store pdfs in my applications (since I'm expecting the pdfs to be around 0.5mb). The tutorial on Paperclip's github didn't one thing clear for me:


  • How do I ask (and actually save) an attachment in my form?



Thank you very much, I really couldn't solve those two problems on my own.

EDIT: This is what I tried

<div class="field">
<%= f.label :pdf %>
<%= f.file_field :pdf %>
</div>


The button to attach a file is there but it seems that it just doesn't work and the file isn't saved.

EDIT2:
Following the suggested solution, now my server is indeed saving the pdfs I attach to my form.

Now I want to understand why the associated url (from a pdf) sends me direct to a page where the system asks where to save the pdf (aka it's downloading it automatically). Here goes the associated part of the code:

<td><%= (link_to 'Related file', task.pdf.url, :target => "_blank") if task.pdf.exists? %></td>


This is located inside app/views/tasks/index.html.erb

Answer

Your migration to add the pdf attachment to a table (In this example I am adding the attachment PDF to a Documents table) should look like this:

class AddAttachmentPdfToDocuments < ActiveRecord::Migration
  def self.up
    change_table :documents do |t|
      t.attachment :pdf
    end
  end

  def self.down
    remove_attachment :documents, :pdf
  end
end

You need to run rake db:migrate after you create this migration so that the pdf column actually gets added to the table.

Your Model code for paperclip (Again, I'm using A documents model for example) should look something like this:

has_attached_file :pdf, :use_timestamp => false
validates_attachment_content_type :pdf, :content_type => ['application/pdf', 'text/plain']

To add a pdf, you need to add an input to your form, for example this is the loop to use to ask for a pdf attachment:

<%= form_for @document do |f| %>

    <%= f.input :title, label: "Title" %>

    <%= f.input :pdf, label: "Upload document:" %>

    <%= f.button :submit %>

<% end %>

In your controler (again using documents as the controler) you need to pass the params :pdf. Your private method would look something like:

def documents_params
    params.require(:document).permit(:title, :pdf)
end

Note, I am using document as my controller, model, form etc, so if you are using a different name you need to change that. If you have problems leave a comment and I will try to help