学生向けプログラミング入門 | 無料

学生向けにプログラミングを無料で解説。Java、C++、Ruby、PHP、データベース、Ruby on Rails, Python, Django

【学習5.0】【Windows】デバイス

メールとパスワードでの認証を作成します。


記述追加 GemFile(56行目)

gem 'devise', '~>4.2'



GemFile

source 'https://rubygems.org'

git_source(:github) do |repo_name|
  repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/")
  "https://github.com/#{repo_name}.git"
end


# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.0.7', '>= 5.0.7.1'
# Use postgresql as the database for Active Record
gem 'pg', '>= 0.18', '< 2.0'
# Use Puma as the app server
gem 'puma', '~> 3.0'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails'
# 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.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 3.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platform: :mri
end

group :development do
  # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
  gem 'web-console', '>= 3.3.0'
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', '~>4.2'



サーバーは「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(55行目)

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.
  if Rails.root.join('tmp/caching-dev.txt').exist?
    config.action_controller.perform_caching = true

    config.cache_store = :memory_store
    config.public_file_server.headers = {
      'Cache-Control' => 'public, max-age=172800'
    }
  else
    config.action_controller.perform_caching = false

    config.cache_store = :null_store
  end

  # 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

  # 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(15,16行目)

<p class="notice"><%= notice %></p>
<p class="alert"><%= alert %></p>



app\views\layouts\application.html.erb

<!DOCTYPE html>
<html>
  <head>
    <title>Gakushuu</title>
    <%= csrf_meta_tags %>

    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_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
24,25行目、39行目のリンクを更新し、21,30,42行目に記述を追加しています。
コードをコピーしてファイルの内容を置き換えて下さい。

<nav class="navbar is-link" role="navigation" aria-label="main navigation">
    <div class="navbar-brand">
        <a class="navbar-item" href="/">
            <h1>テストサイトGakushuu</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-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-info" %>
                        <%= link_to  "ログイン", new_user_session_path, class: "button is-light" %>
                    </div>
                </div>

            <!-- ログインしていたら -->
            <% else %>

                <div class="navbar-item has-dropdown is-hoverable" style="margin-right: 100px;">
                    <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() {

  // navbar burgerアイコンでクリックイベントを確認する
  $(".navbar-burger").click(function() {

      // 「navbar-burger」と「navbar-menu」の両方で「is-active」クラスを切り替えます
      $(".navbar-burger").toggleClass("is-active");
      $(".navbar-menu").toggleClass("is-active");

  });
});
</script>



ルートページを「app\views\pages」フォルダの「about.html.erb」ファイルに設定します。
「config\routes.rb」ファイルに以下の記述を追加します。


記述追加 config\routes.rb(6行目)

root 'pages#about'



config\routes.rb

Rails.application.routes.draw do

  devise_for :users

  # ルートページをapp\views\pages\about.html.erbに設定
  root 'pages#about'

  get 'pages/about'

  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end



ブラウザ確認
http://localhost:3000/


「新規ユーザ登録」ボタンを押します。

新規ユーザ登録
新規ユーザ登録



メールアドレス、パスワードを2回入力して「sign up」ボタンを押します。

サインアップ
サインアップ



ドロップダウンメニューで「ログアウト」できます。

ドロップダウンメニュー
ドロップダウンメニュー



HeidiSQLでユーザテーブルを確認してみます。

ユーザテーブル確認
ユーザテーブル確認