Dirk Bergmann

Developer, panographer. Does consultancy work from own company. Lives in Chiang Mai, Thailand.


Chiang Mai

Hua Hin

Thailand Hotels

ListVote - List. Vote. Learn.

Partnerseek - Find Partners

Populate an ActiveRecord Model with Images Using attachment_fu

Is there anything more painful than manually populating your model with sample data? The thought alone makes most developers? skin scrawl because we write code to do the work for us and abhor manually entering fugacious data.

As always, first things first, watch the relevant Railscast, which will introduce you to populator and faker, both great tools you will soon find indispensable. And here?s a little rake task to populate your model with images, useful to see how it looks with product thumbnails or the like. This is just sample code which you should edit to suit your needs. And attachment_fu has to be configured and working. The file, which could be named attachment_populate.rb belongs in the lib/tasks/ directory:

namespace :attachment do
  desc "Add an image to all MyModel items for visual checking"
  task :add_image_to_all_mymodels  => :environment do
    require 'action_controller'
    require 'action_controller/test_process.rb'
    path = "#{RAILS_ROOT}/public/images/samples/sample.jpg"
    mimetype = "image/jpeg"
    MyModel.find(:all).each do |mymodel| 
      @attachment = Attachment.new(:uploaded_data => ActionController::TestUploadedFile.new(path, mimetype))
      @attachment.mymodel_id = mymodel.id

Call with

rake attachment:add_image_to_all_mymodels

The pertinent documentation is in the #{RAILS_ROOT}/vendor/plugins/attachment_fu/README under ?attachment_fu scripting?:

require 'action_controller'
require 'action_controller/test_process.rb'

path = "./public/images/x.jpg"

mimetype = "image/jpeg"

@attachable = AttachmentMetadataModel.new(:uploaded_data => ActionController::TestUploadedFile.new(path, mimetype))

 And where do you get more info about creating rake tasks? Railscasts of course, who needs books?