User
Thinking about our projects on TODO List. Right now, it's a public TODO List because anyone can come and post stuff. What if we want to have private TODO lists for each user. That's where we need to have a login system for users to log in.
We need to identify a user is with an identifier. And, we need to check password to make sure the user is authorized. We need to store these information in the database.
We are going to name the table User
with two basic attributes username
and password
.
$ rails g model user
In db/migrate/xxxx_create_users.rb
,
class CreateUsers < ActiveRecord::Migration[5.0]
def change
create_table :users do |t|
t.string :username
t.string :password
t.timestamps
end
end
end
Now, that we've created the User
table.
Let's create an API endpoint to create a new user (effectively, this is the same as "Sign Up" on the website).
In config/routes.rb
,
Rails.application.routes.draw do
# ...
# USERS
post '/users' => 'users#create'
# ...
end
In app/controllers/users_controller.rb
,
class UsersController < ApplicationController
def create
@user = User.new(user_params)
if @user.save
render 'users/create'
else
render json: {
success: false
}
end
end
private
def user_params
params.require(:user).permit(:password, :username)
end
end
In app/views/users/create.jbuilder
,
json.user do
json.username @user.username
end
There, our API allows anyone to sign up and create a new account on the website. The account information (username, password) will be stored in the table User
in the database.