Posts Tagged ‘paperclip’

Paperclip and getting the original file path before its uploaded

Tuesday, March 17th, 2009

Back to some rails stuff. Here is a little tip that helped me out with reading in the file that was being uploaded before I saved the record. I was doing this because I wanted to validate the data in the file before I save the record. Here is what I did:

class SomeModel < ActiveRecord::Base
  has_attachment :some_file
 
  def validate
    file = self.some_file.to_file(:original)
    data = File.read(file)
    # Do some validation on data
    errors.add_to_base "File format invalid" if data.nil?
  end
end

Rails TypeError (can’t dump File)

Wednesday, June 18th, 2008

For a while, I kept getting exceptions from my app in the form of “TypeError (can’t dump File):”. I finally found out that this was caused when I was using active_record_store with something like file_column, attachment_fu, or paperclip. Basically whenever you’re storing a file in session, that was too large for the session, you would experience this issue. Here is how to get around it:

Say you have a model like so (This is using file_column):

class Model < ActiveRecord::Base
  file_column :filename
end

Then in your controller you would want to add a line before you redirect off to clear that session:

class Controller < ApplicationController
  def create
    @model = Model.find(params[:model])
 
    @model.save!
    params[:model][:filename] = nil rescue nil   # Reset value here
    redirect_to models_path(@model)
  end
end

As you can see, I am resetting the filename value on the model. Now it shouldn’t complain that it can’t dump the file. Happy RAILSING!