Rails: CarrierWave file uploads

CarrierWave bootstrapCarrierWave file uploads

Installing CarrierWavein your Gemfile

gem 'carrierwave'

CarrierWave provides a generator called uploader to do this to which we pass the name we want to give our uploader, in this case image.

rails g uploader image

edit your show.html.erb which become

Next we’ll need to add the uploader to the Painting model.

rails g scaffold Painting name:string image:string

Next we’ll add the uploader to the Painting model which is done by calling the mount_uploader method

class Painting < ActiveRecord::Base
    
  attr_accessible :name, :image
  mount_uploader :image, ImageUploader
end

and then in your app/views/paintings/_form.html.erb edit your code, which become

  <div class="control-group">
    <%= f.label :image, :class => 'control-label' %>
    <div class="controls">
        <%= f.file_field :image, :class => 'text_field' %>
   </div>
  </div>

edit your show.html.erb which become

<dd><%= image_tag @painting.image_url.to_s %></dd>

Uploading Image via URL
adding line in _form.html.erb

<div class="control-group">
  <%= f.label :image, "or image URL", :class => 'control-label' %>
    <div class="controls">
     <%= f.text_field :remote_image_url %>
    </div>
  </div>

As we’ve added a field to the painting form we’ll need to add it to the list of attr_accessible fields in the Painting model

class Painting < ActiveRecord::Base
  attr_accessible :name, :image,  :remote_image_url
 
  mount_uploader :image, ImageUploader
end
Advertisements

One thought on “Rails: CarrierWave file uploads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s