How to set a file upload programmatically using Paperclip

Ruby on-RailsRubyPaperclipFile Upload

Ruby on-Rails Problem Overview


I have a rake task to seed an application with random data using the faker gem. However, we also have images (like logos) that we want uploaded in this rake task.

We already have Paperclip set up, but don't have a way to upload them programmatically in a rake task. Any ideas?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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.new
file = File.open(file_path)
my_model_instance.attachment = file
file.close
my_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 :attachment
end

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

Solution 2 - Ruby on-Rails

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.save
end

I hope this helps!

Solution 3 - Ruby on-Rails

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.new
my_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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJarylView Question on Stackoverflow
Solution 1 - Ruby on-RailstheIVView Answer on Stackoverflow
Solution 2 - Ruby on-RailsjonniiView Answer on Stackoverflow
Solution 3 - Ruby on-RailswinfredView Answer on Stackoverflow