Rails Tip #08 - Paperclip and Image magik for images

in ruby •  7 years ago  (edited)

Thanks to a follower's suggestion, from now onwards i will use #bilaltutorials tag for my articles.

Adding images to rails app

The Task

Add image field to posts and save those images for later use

Preparing for it

  • 1- install image magik
sudo apt-get -y install imagemagick gsfonts

check to see if it is installed

which convert

typing above command should return the following output
Screenshot from 2018-05-04 02-11-22.png

  • 2- add paperclip gem in gemfile
gem "paperclip", "~> 6.0.0"

and do bundle install

  • 3- create migration
rails generate paperclip post cover_photo
  • 4- rake db:migrate

  • 5- open Post model and add following

  has_attached_file :cover_photo, styles: {large: "600x600>", medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png"
  validates_attachment_content_type :cover_photo, content_type: /\Aimage\/.*\z/

  • 6- update environment variables to use image magik
    in config/environments/development.rb
Paperclip.options[:command_path] = "/usr/local/bin/"
  • 7- Edit forms
<%= form_for @post, url: posts_path, html: { multipart: true } do |form| %>
  <%= form.file_field :cover_photo %>
  <%= form.submit %>
<% end %>
  • 8- Permit controller to accept new form field
params.require(:post).permit(:title,:cover_photo,:content)

That's all you need to do :) and voila you have images added to your posts.

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

Thanks for sharing bro ❤ @bilal-haider

You are also a programmer ?