While learning Ruby on Rails, a user named devise can easily create new registration, login function, etc. just by installing gem. It's very good.
Gemfile
gem 'devise'
It should be noted here that devise
is not device
When I was a programming super beginner, I got an error due to this misspelling.
We will install the gem here, so do $ bundle install
on the command line
Also, there is an installation command for devise, so execute it.
Terminal
$ rails g devise install
This completes the devise installation.
Set the database type and constraints based on the information described in the migration file.
Terminal
$ rails g devise user
When you usually create a model with Rails application, you can create a model by typing the command $ rails g model user
, but here we will create a model with the devise command.
After executing this command, it is successful if model / user.rb
and the migration file for user are created.
In the user's migration file
20200603_devise_create_users.rb
class DeviseCreateUsers < ActiveRecord::Migration[5.0]
def change
create_table :users do |t|
## Database authenticatable
t.string :name, null: false
t.string :email, null: false, default: ""
t.string :encrypted_password, null: false, default: ""
#~abridgement~
end
add_index :users, :name, unique: true
#add so that all user information can be searched_Paste index
The name column, email column, etc. are set, and each is restricted by null: false, and if it is null, an error will be displayed when a new user is registered.
Let's also validate user.rb.
user.rb
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
validates :name, presence: true, uniqueness: true
#Validation is applied so that the name column is not empty and duplicate names cannot be registered.
end
Various restrictions can be set for validation, and if you want to know more, click here! https://qiita.com/h1kita/items/772b81a1cc066e67930e
This completes the settings for the migration file and model associated with the database.
Terminal
$ rails db:migrate
Let's migrate the migration file.
View files can also be created with a single devise command.
Terminal
$ rails g devise:views users
This is easy, but we have implemented new user registration and login functions.
Recommended Posts