Saturday, March 1, 2014

Displaying/Updating images in Rails

As I mentioned in a previous post, installing Paperclip is the first step to being able to display an image in Rails. However, in order to size or scale the image for storage and display, you need to use ImageMagick. If you are on a Mac (as I am), there is a handy package you can download at http://cactuslab.com/imagemagick/. There are other websites with instructions for installing ImageMagick on Linux and Windows machines as well.

Then, assuming you have Paperclip added into your Rails code, add the "styles:" components to the has_attached_file method in the model where you will be storing the image using Paperclip. For example:

  has_attached_file :avatar,
    :styles => {:large => "300x300#"}, 
    :default_url => "avatar_blank.png"

Then open the Rails console by running "rails c" and type the following command to reprocess any images stored in the database prior to the installation of ImageMagick. The command to run is

<ModelNameHere>.find_each{|u| u.avatar.reprocess!}

This will reprocess all the images already in the database and from now on, images uploaded will be saved by the style you gave them. Then, when displaying the image using "image_tag", you can do:

image_tag @<instance_variable_here>.avatar.url(:large)

and display the cropped picture.

No comments:

Post a Comment