You will learn how to add paperclip gem in ruby on rails
You will learn how to upload images using paperclip gem in ruby on rails
Requirements
OS: Ubuntu/Mac OS
A text editor like sublime
Basic understanding about Ruby on Rails
And for better understanding must refer my previous tutorials (link added to the curriculum)
Difficulty
Intermediate
Tutorial Contents
Hello and welcome to the next part of the tutorial. In this tutorial, we will learn how to upload images in ruby on rails project. So let's start our tutorial,
Open the terminal and go to your project path that was build in our previous tutroials. If you haven't go through the previous tutroials, please refer those also.
And now start rails server by entring the following command:
railss
Now open the project in the text editor like sublime text editor.
Now go to the Gemfile and add the following gem and then saved it.
gem"paperclip"
Next go to the terminal and stop the server then run the following command and also start the server again
bundle
Bundle command will install the paerclip gem into your project
Once we successfully install the gem, the next step to add code so that our project will accept the images.
You alredy know that we have built a simpe application till now. We have users table in which all the user details are stored but we haven't store the profile picture.
So for that we have to add image column to the users table.
Go to the terminal and stop the server and run the following command:
railsgmigrationadd_image_to_users
The above command will generate a migaration names timestamp_add_image_to_users under the db folder of the proejct. Now go to this migration file and add following code:
Paste that code in the form and refresh the form. Now you will see the add avatar option as shown in the below image
Next step is to save this avatar into the database, for that we have to permit the params in the users controller. Go to users > registration_controller and add permit params in the configure_sign_up_params method
And also we have to tell the user model is to handle the avatar for that add the following code to the user model