[05]ナビゲーションバー(Bulma) << [ホームに戻る] >> [07]氏名認証
メールとパスワードでの認証を作成します。
記述追加 GemFile(60行目)
gem 'devise'
GemFile
source 'https://rubygems.org' git_source(:github) { |repo| "https://github.com/#{repo}.git" } ruby '2.6.3' # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' gem 'rails', '~> 6.0.3' # Use postgresql as the database for Active Record gem 'pg', '>= 0.18', '< 2.0' # Use Puma as the app server gem 'puma', '~> 4.1' # Use SCSS for stylesheets gem 'sass-rails', '>= 6' # Transpile app-like JavaScript. Read more: https://github.com/rails/webpacker gem 'webpacker', '~> 4.0' # Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks gem 'turbolinks', '~> 5' # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder gem 'jbuilder', '~> 2.7' # Use Redis adapter to run Action Cable in production # gem 'redis', '~> 4.0' # Use Active Model has_secure_password # gem 'bcrypt', '~> 3.1.7' # Use Active Storage variant # gem 'image_processing', '~> 1.2' # Reduces boot times through caching; required in config/boot.rb gem 'bootsnap', '>= 1.4.2', require: false group :development, :test do # Call 'byebug' anywhere in the code to stop execution and get a debugger console gem 'byebug', platforms: [:mri, :mingw, :x64_mingw] end group :development do # Access an interactive console on exception pages or by calling 'console' anywhere in the code. gem 'web-console', '>= 3.3.0' gem 'listen', '~> 3.2' # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring gem 'spring' gem 'spring-watcher-listen', '~> 2.0.0' end group :test do # Adds support for Capybara system testing and selenium driver gem 'capybara', '>= 2.15' gem 'selenium-webdriver' # Easy installation and use of web drivers to run system tests with browsers gem 'webdrivers' end # Windows does not include zoneinfo files, so bundle the tzinfo-data gem gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby] # Bulma gem 'bulma-rails', '~> 0.7.4' gem 'bulma-extensions-rails', '~> 1.0.30' #デバイス gem 'devise'
サーバーは「Ctr+C」で「y」を入力するとストップできます。
コマンド
bundle
デバイスのインストールをします。
コマンド
rails g devise:install
このときに表示される手順通りに進めていきます。
コマンド(3つ)
rails g devise user
rails g devise:views
rails db:migrate
「config\environments\development.rb」ファイルに以下の記述を追加します。
記述追加 config\environments\development.rb(64行目)
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
config\environments\development.rb
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Do not eager load code on boot. config.eager_load = false # Show full error reports. config.consider_all_requests_local = true # Enable/disable caching. By default caching is disabled. # Run rails dev:cache to toggle caching. if Rails.root.join('tmp', 'caching-dev.txt').exist? config.action_controller.perform_caching = true config.action_controller.enable_fragment_cache_logging = true config.cache_store = :memory_store config.public_file_server.headers = { 'Cache-Control' => "public, max-age=#{2.days.to_i}" } else config.action_controller.perform_caching = false config.cache_store = :null_store end # Store uploaded files on the local file system (see config/storage.yml for options). config.active_storage.service = :local # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = false config.action_mailer.perform_caching = false # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise an error on page load if there are pending migrations. config.active_record.migration_error = :page_load # Highlight code that triggered database queries in logs. config.active_record.verbose_query_logs = true # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. config.assets.debug = true # Suppress logger output for asset requests. config.assets.quiet = true # Raises error for missing translations. # config.action_view.raise_on_missing_translations = true # Use an evented file watcher to asynchronously detect changes in source code, # routes, locales, etc. This feature depends on the listen gem. # config.file_watcher = ActiveSupport::EventedFileUpdateChecker # デバイスのメール設定 config.action_mailer.default_url_options = { host: 'localhost', port: 3000 } end
「app\views\layouts\application.html.erb」ファイルに以下の記述を追加します。
記述追加 app\views\layouts\application.html.erb(16行目)
<p class="notice"><%= notice %></p> <p class="alert"><%= alert %></p>
app\views\layouts\application.html.erb
<!DOCTYPE html> <html> <head> <title>Oshigoto</title> <%= csrf_meta_tags %> <%= csp_meta_tag %> <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %> <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %> </head> <body> <%= render "shared/navbar" %> <p class="notice"><%= notice %></p> <p class="alert"><%= alert %></p> <%= yield %> </body> </html>
ナビゲーションバーに「新規ユーザ登録」「ログイン」「ログアウト」のリンクを追加します。
記述更新 app\views\shared\_navbar.html.erb
36,37行目、45行目、51行目のリンクを更新し、33,42,54行目に記述を追加しています。
コードをコピーしてファイルの内容を置き換えて下さい。
<nav class="navbar is-danger" role="navigation" aria-label="main navigation"> <div class="navbar-brand"> <a class="navbar-item" href="/"> <h1>テストサイトOshigoto</h1> </a> <a role="button" class="navbar-burger burger" aria-label="menu" aria-expanded="false" data-target="navbarBasicExample"> <span aria-hidden="true"></span> <span aria-hidden="true"></span> <span aria-hidden="true"></span> </a> </div> <div id="navbarBasicExample" class="navbar-menu"> <div class="navbar-start"> <div class="navbar-item"> <div class="field has-addons"> <div class="control"> <input class="input" type="text" placeholder="どんなお仕事を?"> </div> <div class="control"> <a class="button is-success">検索</a> </div> </div> </div> </div> <div class="navbar-end"> <a class="navbar-item"></a> <a class="navbar-item"></a> <!-- もしログインしていなかったら--> <% if (!user_signed_in?) %> <div class="navbar-item"> <div class="buttons"> <%= link_to "新規ユーザ登録", new_user_registration_path, class: "button is-primary" %> <%= link_to "ログイン", new_user_session_path, class: "button is-light" %> </div> </div> <!-- ログインしていたら --> <% else %> <div class="navbar-item has-dropdown is-hoverable"> <a class="navbar-item"><%= current_user.email %></a> <div class="navbar-dropdown"> <a href="" class="navbar-item"></a> <a href="" class="navbar-item"></a> <hr class="navbar-divider"> <%= link_to "ログアウト", destroy_user_session_path, method: :delete, class: "navbar-item" %> </div> </div> <% end %> </div> </div> </nav> <script> $(document).ready(function() { // Check for click events on the navbar burger icon $(".navbar-burger").click(function() { // Toggle the "is-active" class on both the "navbar-burger" and the "navbar-menu" $(".navbar-burger").toggleClass("is-active"); $(".navbar-menu").toggleClass("is-active"); }); }); </script>
ルートページを「app\views\pages」フォルダの「home.html.erb」ファイルに設定します。
「config\routes.rb」ファイルに以下の記述を追加します。
記述追加 config\routes.rb(4行目)
root 'pages#home'
config\routes.rb
Rails.application.routes.draw do # ルートを app\views\pages\home.html.erb に設定 root 'pages#home' devise_for :users get 'pages/home' # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html end
ブラウザ確認
http://localhost:3000/
「新規ユーザ登録」ボタンを押します。
メールアドレス、パスワードを2回入力して「sign up」ボタンを押します。
ドロップダウンメニューで「ログアウト」できます。
Posticoでユーザテーブルを確認してみます。
↓↓クリックして頂けると励みになります。