Toll free (US) : +1 (888) 838-3532 | NYC: +1 (646) 491-6866

If we are building a web application, one of the features we would definitely want is the image uploading feature. In fact, image uploading is one important feature that the modern-day applications can simply not be imagined without. And not just that, it is even more important considering the fact that images uploading also plays a role in search engine optimization.

CarrierWave gem can be integrated with our Rails applications and it provides a simple and extremely flexible way to upload files.

Rails Application Setup:

To set this up in our Rails Application, after creating a new project, we need to add 2 gems in the gem file. The first is CarrierWave itself, and the second is the bootstrap-sass gem(optional).

Installation:

We run bundle install and then create our models and controllers for our application.
bundle install

rails g controller controllername action => index new create destroy
Now, we need to create an uploader. The uploaders tell carrierwave how to handle the file once it’s uploaded
=> rails g uploader attachment
It will create a folder named uploaders in the app folder with a file attachment_uploader.rb.

How you play with it:

app/uploaders/attachment_uploader.rb

Now in our resumes controller and add some code to handle form processing:

Now we need to set up our view files:

For new.html.erb

<%= form_for @resume, html: { multipart: true } do |f| %> <%= f.label :name %> <%= f.text_field :name %> <%= f.label :attachment %> <%= f.file_field :attachment %> <%= f.submit “Save”, class: “btn btn-primary” %> <% end %>

 

For index.html.erb

<% @resumes.each do |resume| %>

<% end %>

Name Download Link
<%= resume.name %> <%= link_to “Download Resume”, resume.attachment_url %> <%= button_to “Delete”, resume, method: :delete, class: “”, confirm: “Are you sure that you want to delete #{resume.name}?” %>

 

app/uploaders/attachment_uploader.rb

References:

Github: https://github.com/carrierwaveuploader/carrierwave
RubyGems: https://rubygems.org/gems/carrierwave/versions/0.11.2
Railscasts: http://railscasts.com/episodes/253-carrierwave-file-uploads

WhatsApp chat