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
- 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.
Thanks for sharing bro ❤ @bilal-haider
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
You are also a programmer ?
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit