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

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

Rails6.1 | 民泊予約アプリ作成 | 05 | deviceの利用

↓↓クリックして頂けると励みになります。


04 | Bootstrap5.3の利用】 << 【ホーム】 >> 【06 | ナビゲーションバーの利用



Ruby on Railsでログインを実装する時、「device」を活用すると素早く実装することができます。
deviseはユーザーの登録、ログイン、ログアウト、パスワードリセットなどの認証機能があり、Gメールの設定をすることで、セキュリティが向上します。

バージョン4.8をGemFileに記述します。

記述追記 【Gemfile】

gem 'devise', '~> 4.8', '>= 4.8.1'



バンドルします。
コマンド
bundle


デバイスをインストールします。
コマンド
rails g devise:install


次のようなインフォメーションがでますので、その流れに沿って進めていきます。

===============================================================================

Depending on your application's configuration some manual setup may be required:

  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.

     * Required for all applications. *

  2. Ensure you have defined root_url to *something* in your config/routes.rb.
     For example:

       root to: "home#index"
     
     * Not required for API-only Applications *

  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>

     * Not required for API-only Applications *

  4. You can copy Devise views (for customization) to your app by running:

       rails g devise:views
       
     * Not required *

===============================================================================



まず、ユーザーテーブルを作ります。
コマンド
rails g devise user

ユーザーテーブル作成
ユーザーテーブル作成



ビューを作成します。
コマンド
rails g devise:views

ビュー作成
ビュー作成



マイグレーションを適用します。
コマンド
rails db:migrate


メールが送れるように設定します。
これは開発環境での設定になります。
「config\environments\development.rb」ファイルの末尾に以下の記述を追加します。

  # デバイスのメール設定
  config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }



記述追加 【config\environments\development.rb】78行目

require "active_support/core_ext/integer/time"

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 any time
  # it changes. 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 exceptions for disallowed deprecations.
  config.active_support.disallowed_deprecation = :raise

  # Tell Active Support which deprecation messages to disallow.
  config.active_support.disallowed_deprecation_warnings = []

  # 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.i18n.raise_on_missing_translations = true

  # Annotate rendered view with file names.
  # config.action_view.annotate_rendered_view_with_filenames = 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

  # Uncomment if you wish to allow Action Cable access from any origin.
  # config.action_cable.disable_request_forgery_protection = true

  # デバイスのメール設定
  config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }  

end



「app\views\layouts\application.html.erb」ファイルのbodyタグに以下の記述を追加します。

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



記述追加 【app\views\layouts\application.html.erb】19行目

<!DOCTYPE html>
<html>
  <head>
    <title>VacationRental</title>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <%= stylesheet_pack_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>

    <!-- bootstrap5.3 -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-geWF76RCwLtnZ8qwWowPQNguL3RmwHVBC9FhGdlKrxdiJJigb/j/68SIy3Te4Bkz" crossorigin="anonymous"></script>
  </head>

  <body>
    <!-- device -->
    <p class="notice"><%= notice %></p>
    <p class="alert"><%= alert %></p>

    <%= yield %>
  </body>
</html>



Webサーバーを起動して表示を確認してみます。
http://localhost:3000/users/sign_up


まだダサいですがサインアップは機能します。

デフォルトデザイン
デフォルトデザイン



サインアップしてみます。
メールアドレスとパスワードを2回入力し、「Sign_up」をクリックします。

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



Posticoでユーザー登録ができているか確認します。

データベース確認
データベース確認



04 | Bootstrap5.3の利用】 << 【ホーム】 >> 【06 | ナビゲーションバーの利用


↓↓クリックして頂けると励みになります。