visit
As a student of Microverse, I’ve reached the point where Rails’ framework was introduced to me. It appeared to me with the best omens on its hands. Ruby on Rails is a starting point for many start-ups because all of them got blinded by its beauty and simplicity. I have to admit that I felt intimidated for a while. Surely I can't say we are the best friends now but things started to make sense. Ruby on Rails is designed under the MVC principles - Model View Controllers.
Devise is a flexible authentication solution for Rails
As things started to get more advanced, after 4 months of coding in Microverse, the time has come to create something real. But wait, how do they include user functionality in applications? Where are the credentials being kept and how can I make it happen without re-inventing the wheel.
Those types of questions kept spinning in my mind in the beginning. Fellow students advised me to calm down and spend time on documentation. Rails' world is surrounded by libraries called gems. There is a gem for anything you can think of. Without wasting more time let's see Devise magic in action. Let's create a Rails app together.
rails new devise_gem
rails g scaffold Post post:text
rails db:migrate
rails s
update routes => config/routes.rb - root 'posts#index'
restart the server always after modifying routes files or controllers files
Visit Gemfile in the root folder of your application
Add devise gem in the general dependencies(this means anywhere outside of groups. Yes, you can put it between the comments. You can also leave your comment above in case you forget what this is.
[EXTRA TIP]: Visit rubygems.org. It will be your friend from now on.
gem ‘devise’
Back in the terminal and bundle install to get the devise dependencies in your project.
On this step, we need to set up devise for our application. It simple but make sure you won't miss any step while doing that. (Did that a few times)Lastly, after running all the commands, we have to do one more! Don't yell at me now with all your complaints. All of them are necessary for different reasons.rails g devise:install
Devise installation will ask you to follow some extra steps. Please, execute it one by one. Remember that we have already set our route file and even though it's not as devise tells us, don't get confused, because devise gives us an example. This mean there are only 3 steps left.
rails g devise User
That was all. You have everything that you need in order to have your User functionality in your application. From now on, everything has to do with the way you want to use it. I will show you some basic things but feel free to test it yourself.
visit app/controllers/posts_controller.rb
Inside the class and in the top let's add one line:
before_action :authenticate_user!, except: [:index, :show]
This tells to our application that
users -meaning the ones that haven’t been registered in our database- can only visit our index and show page.un-authenticated
By default,
devise gem has only email and password as fields
. If we want to have other fields as well - which we will do now - we need to do some things. Create RegistrationsController - (app/controllers/registrations_controller.rb)
class RegistrationsController < Devise::RegistrationsController
private
def sign_up_params
params.require(:user).permit(:name, :username, :email,:password, :password_confirmation)
end
def account_update_params
params.require(:user).permit(:name, :username, :email,:password, :password_confirmation, :current_password)
end
Then, we have to update our routes with our new controller (
config/routes.rb
)devise_for :users, controllers => { registrations: 'registrations' }
Next, let’s create a migration file with the new fields we want to request from the user. Up to now, they weren't in our database and we want to include them in case you didn't get it yet.
rails g migration AddFieldsToUser - CamelCase
rails g migration add_fields_to_user - snake_case
Both of them do exactly the same job. Choose whatever suits better for you but be careful while typing. Everything matters on Rails.
Check migration file cause we want to include some lines of code there.Inside the change method:
add_column :users, :name, :string
add_column :users, :username, :string
add_index :users, :username, unique: true
You may have noticed that we haven't done anything with our database since we generated our scaffold Post model. Until now, we are still dealing with the user setup and devise configuration itself. I'm sure that you are thinking that all these were too much but surely it's worth our time because if we wanted to do that all these methods on our own, we would have spent double time.
Time for our migrations now:rails db:migrate
From now on, we have new fields in our table, and we need to update our views located in the devise folder.
app/views/devise/registrations/new.html.erb.
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name, autofocus: true %>
</div>
<div class=“field">
<%= f.label :username %><br />
<%= f.text_field :username %>
</div>
Create associations between controller && model
app/model/user.rb
User model
has_many :posts
# app/model/post.rb
Post Model
belongs_to :user
rails g (generate) migration AddUserIdToPosts user_id:integer
Migration file should look like this:
def change
add_column :posts, :user_id, :integer
end
After that being done, we have to configure our post_controller to work with Devise.
def new
@post = current_user.posts.build
end
def create
@post = current_user.posts.build(post_params)
end
I know that I've said that again but keep in mind that it's always a good idea whenever you are making changes either to the controller or the routes to restart the server in your terminal to be sure that all of the changes are now loaded in the application. If you try now to create a new Post as this is our root page you will arrive at the login page. Of course, we haven't created any user up to now. Let's do that if we want to enter our app and create some posts!
Basic things are introduced in this article. I was fascinated by the simplicity and how logical are things in Ruby thus in Ruby on Rails. There were cases where I felt like writing an essay to someone. If you haven't tried it out yet I strongly recommend you to spend some time with it.
Last but not least, completely unrelated with the topic of this article but I thought it would be a good idea to add it as a conclusion. Remember that our minds love to play games with us. We want to learn everything at once. We are comparing ourselves with other people. We are feeling intimidating. Imposter Syndrome has huge impact in our life as developers. Rails may be outdated but if you are good at it, you will surely be of need. Choose your path and stay focused.Be healthy both physically and mentally!Photo credits: Zane Lee