How to set a file upload programmatically using Paperclip How to set a file upload programmatically using Paperclip ruby ruby

How to set a file upload programmatically using Paperclip


What do you mean by programmatically? You can set up a method that will take a file path along the lines of

my_model_instance = MyModel.newfile = File.open(file_path)my_model_instance.attachment = filefile.closemy_model_instance.save!

#attachment comes from our Paperclip declaration in our model. In this case, our model looks like

class MyModel < ActiveRecord::Base  has_attached_file :attachmentend

We've done things similar to this when bootstrapping a project.


I do something like this in a rake task.

photo_path = './test/fixtures/files/*.jpg'Dir.glob(photo_path).entries.each do |e|  model = Model.find(<query here>)          model.attachment = File.open(e)  model.saveend

I hope this helps!


I didn't actually have to write a method for this. Much simpler.

In Model ->

Class Model_Name < ActiveRecord::Base  has_attached_file :my_attachment,  :params_for_attachment

In seed.db ->

my_instance = Model_name.newmy_instance.my_attachment = File.open('path/to/file/relative/to/app')my_instance.save!

Perhaps the previous answers meant to use the name of the attachment as defined in the model (rather than writing a method Model_name.attachment).Hope this is clear.