Rails 3 Image Uploading with Carrierwave
Posted by 10 days ago • Comments (0)
Carrierwave seems like a tidy alternative to paperclip for file uploads in ruby frameworks. The first step is to add the gem to your application in the Gemfile:
#Gemfile
gem "carrierwave"
After installing the gem with the bundle command we can generate an uploader, in this example i want to build a simple image uploader using a post class:
$> rails g uploader image
That should generate an image_uploader.rb file. Before we configure that lets create and run the migration needed to alter the database.
$> rails g migration add_image_to_posts image:string
$> rake db:migrate
Now we need to add the uploader to the post class:
#post.rb
class Post < ActiveRecord::Base
mount_uploader :image, ImageUploader
end
Next up, we need to add the file field mark-up to the view template:
#_form.html.erb
<%= f.file_field :image %>
Then to make the form handle uploads we need to make it multipart:
#_form.html.erb
<%= form_for @post, :html => {:multipart => true} do |f| %>
Now to display the image in the view template:
#index.html.erb
<%= image_tag post.image_url.to_s %>
That works but unless you edit the dimensions before you upload, the image will display in it's native size. We can process the image with carrierwave and the rmagick gem, you'll also need imagmagik installed on your system. Here i want a thumb version of the image which should be 150x150px:
#Gemfile
gem "rmagick"
#image_uploader.rb
include CarrierWave::RMagick
# Create different versions of your uploaded files:
version :thumb do
process :resize_to_limit => [150, 150]
end
#index.html.erb
<%= image_tag post.image_url(:thumb).to_s %>
Be sure to check the documentation and checkout the railscasts episode.
















