Hello! This is Yori-goreng who is learning Rails: sunny:
In this article, we will introduce the introduction of devise
, which controls the login function, and user permissions: relaxed:
If you want to know more details, please see the following reference articles.
--Reference article
https://qiita.com/cigalecigales/items/f4274088f20832252374
https://qiita.com/tobita0000/items/866de191635e6d74e392
It is one of the Ruby gems, and you can easily implement the login function by using devise
.
Create an app with rails new app name
.
For now, let's name it devise_test.
rails new devise_test
cd devise_test
rails db:create
Add devise gem to gemfile
.
gem 'devise'
Install gem.
bundle install
rails g devise:install
If you see a long sentence like the one below in your terminal, you are successful.
===============================================================================
Some setup you must do manually if you haven't yet:
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
===============================================================================
Create a User model with the following command.
rails g devise user
Performing a migration at this point completes a simple login page.
rails db:migrate
rails s
After rails s
, open the login page at http: // localhost: 3000 / users / sign_in.
2.4. before_action :authenticate_user!
If you write before_action: authenticate_user!
in the controller, the processing performed here can be executed only by the logged-in user.
As an example, create a Homes controller.
rails g controller homes index
Add before_action: authenticate_user!
to the created homes_controller.rb
.
app/controllers/home_controller.rb
class HomesController < ApplicationController
before_action :authenticate_user!
def index
end
end
This allows only the logged-in user to see the list display by the index action.
Recommended Posts