The other day, I introduced devise with the implementation of login authentication, so I will keep a record.
A gem package for introducing the login authentication function. You can easily implement sign-in, sign-out, sign-up (email authentication is possible), etc.
Install devise. Add to Gemfile and execute bundle install.
Gemfile
gem 'devise'
$ bundle install
After the installation is complete, create the file. Running rails g devise: install
will create the related files.
$ rails g devise:install
When executed, it will be displayed like this.
1. Ensure you have defined default url options in your environments files. Here
is an example of default_url_options appropriate for a development environment
in config/environments/development.rb:
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
In production, :host should be set to the actual host of your application.
2. Ensure you have defined root_url to *something* in your config/routes.rb.
For example:
root to: "home#index"
3. Ensure you have flash messages in app/views/layouts/application.html.erb.
For example:
<p class="notice"><%= notice %></p>
<p class="alert"><%= alert %></p>
4. You can copy Devise views (for customization) to your app by running:
rails g devise:views
To summarize briefly
For the time being, let's display the notification and alert messages of 3.
In ʻapplication.html.erb
<%= notice %>
Added
<% = alert%> </ p>`.
ruby:application.html.erb
<!DOCTYPE html>
<html>
<head>
<title>App</title>
<%= csrf_meta_tags %>
<%= csp_meta_tag %>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
</head>
<body>
<p class="notice"><%= notice %></p>
<p class="alert"><%= alert %></p>
<%= yield %>
</body>
</html>
Create an authentication model and migration file with rails g devise model name
.
$ rails g devise user
After creating the model and migration file, run rails db: migrate
.
$ rails db:migrate
That's it. You can now use the authentication function using devise.
When editing the view file
$ rails g device:views
Doing this creates a view that you can edit as needed.
Recommended Posts