I’ve been using the file_column plugin for Ruby on Rails in the last days, so here’s some handy notes on the subject:

Installing is pretty straightfoward, just like the majority of Rails plugins:

script/plugin install http://opensvn.csie.org/rails_file_column/plugins/file_column/trunk

The first thing we need is to tell our model which column to use:

class Blog < ActiveRecord::Base
    file_column :image
end

Now, if we want to include a upload mechanism in our form, we need to include some code like this:

<%= file_column_field "blog", "image" %>

form upload

On our views, we can use the following to show our image:

<%= image_tag url_for_file_column("blog", "image") %>

view column

We can extend things further, like for instance, I may want to upload only “jpg” and “gif” images and I want them to have a certain size:

class Blog < ActiveRecord::Base
 file_column :image
 validates_file_format_of :image, :in => ["gif", "jpg"]
 validates_filesize_of :image, :in => 1.kilobytes..5000.kilobytes
end

Now let’s use RMagick (see previous post) to do some image manipulations, like creating two aditional images with different sizes based on the image we uploaded, one which we shall name “peq” with a 86×71 pixel dimensions and another named “med” with a 289×258 pixel dimensions, I found out from the wiki that the crop parameter conveniently preserves the center of an image, removing space from the edges to reach the target width/height ratio:

class Blog < ActiveRecord::Base
  file_column :image, 
:store_dir => "public/images/my_stupid_place_to_keep_images_uploaded",
  :magick => {:versions => {
         :thumb => {:crop => "1:1",  :size => "86x87!", :name => "peq"},
         :normal => {:crop => "1:1", :size => "289x258!", :name=>"med"}
         }
       }
end

uploaded files

So, by default file_column will save images with the following scheme:

myApp/public/[Model name]/[file_column field name]/[record id]/[image filename]

but as I showed you, it’s possible to define a different storage directory in your model.

Now let’s access the smaller images we saved with RMagick, on our views:

<%= image_tag url_for_file_column("blog", "image", "peq") %>
or
<%= image_tag url_for_file_column("blog", "image", "med") %>

Other interesting information, you can access your image information in several ways:

>> p.image
=> “public/images/my_stupid_place_to_keep_images_uploaded/267/MyPicture.jpg”

>> p.image(”peq”)
=> “public/images/my_stupid_place_to_keep_images_uploaded/267/peq/MyPicture.jpg”

>> p.image_relative_path
=> “267/MyPicture.jpg”

>> p.image_relative_path(”peq”)
=> “267/peq/MyPicture.jpg”

>> File.basename(p.image)
=> “MyPicture.jpg”

More information on the subject:

There’s other alternatives for uploading images and files but I felt file_column is a good and easy solution for most cases.