PaperClip Gem for uploading images
Rails has several gems available on github that allows you to handle image upload functionality. PaperClip gem is one of the these gems and it is widely used in many rails applications.
Starting point for adding PaperClip gem to you project is your Gemfile where you need to add
gem "paperclip", "~> 4.3"
After saving Gemfile you need to install this Gem by running
> bundle install
Next step, you need to add Image model to your database via migration file
class CreateImages < ActiveRecord::Migration
def change
create_table :images do |t|
t.string :file_name, :null => false
t.string :title
end
end
end
Your image class that will have to be update with the following attributes "as has_attached_file" and " validates_attachment_content_type". Please see example below.
class Image < ActiveRecord::Base
has_attached_file :asset, :styles => { :medium => "300x300>", :thumb => "100x100>" }, :default_url => "/images/:style/missing.png"
validates_attachment_content_type :asset, :content_type => /\Aimage\/.*\Z/
end
Rails on Windows may require ImageMagick installed in order to proceed with the PaperClip Gem. Installation should be seamless and you can download installation file from http://www.imagemagick.org/script/binary-releases.php
Adding reference after you install ImageMagick to your GnuWin32\bin location is required on Windows computer to your config/environment/development.rb file
#Adding Paperclip reference to GnuWin32
Paperclip.options[:command_path] = 'C:\Program Files (x86)\GnuWin32\bin'
Installation of GnuWin32 program has to happen before hand in order to kick start PaperClip working on Windows machines.
Finally, you need to add form field to your Rails application and your app is ready to handle image upload
<div class="field">
<%=f.label :image%>
<%=f.file_field :asset, :class => "form-control"%>
</div>
You can always see PaperClip in action by watching RailCast video on PaperClip implementations.
Adding multiple images via PaperClip tutorial is another good resource to get you started