LoginSignup
0
0

More than 3 years have passed since last update.

Rails 自作アプリへの道 Part1

Last updated at Posted at 2020-03-29

Rails 自作アプリを作った時の経過をまとめていきます。

環境

OS Ruby Rails
Mac Mojave 10.14.16 2.6.3p62 5.0.7.2

参考
https://qiita.com/cigalecigales/items/f4274088f20832252374

前提
環境構築済

【devise】

1.Gemのインストール

①プロジェクトの作成

プロジェクトを作成する。

$ rails _5.0.0.1_ new ticket2_app -d mysql
$ cd ticket2_app
$ rails -v
(省略)
Rails 5.0.7.2

②Gemfileの編集とインストール

以下ファイルにdeviseとomniauth-twitterを追加する。

Gemfile
source 'https://rubygems.org'

(省略)...

# Devise
gem 'devise'

gemをインストールする。

$ bundle install

2.deviseの設定

①devise関連ファイルを追加する。

$ rails g devise:install

Running via Spring preloader in process 48887
      create  config/initializers/devise.rb
      create  config/locales/devise.en.yml
===============================================================================

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

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

②デフォルトURLの指定

config/environments/development.rb

Rails.application.configure do
  # Settings specified here will take precedence over those in config/application.rb.

  (省略)...

  # mailer setting
  config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
end

③root_urlの指定

$ rails g controller Pages index show
config/routes.rb

Rails.application.routes.draw do
  root 'pages#index'
  get 'pages/show'
  (省略)...
end

④flashメッセージの設定

app/views/layouts/application.html.erb

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

  <%= 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>

⑤DeviseのViewを生成

$ rails g devise:views

3.Userモデルの設定

①Userモデルの作成

$ rails g devise Seller
db/migrate/20200331113140_devise_create_sellers.rb

class DeviseCreateSellers < ActiveRecord::Migration[5.0]
  def change
    create_table :sellers do |t|
      ## Database authenticatable
      t.string :email,              null: false, default: ""
      t.string :encrypted_password, null: false, default: ""

      ## Recoverable
      t.string   :reset_password_token
      t.datetime :reset_password_sent_at

      ## Rememberable
      t.datetime :remember_created_at

      ## Trackable
      t.integer  :sign_in_count, default: 0, null: false
      t.datetime :current_sign_in_at
      t.datetime :last_sign_in_at
      t.string   :current_sign_in_ip
      t.string   :last_sign_in_ip

      ## Confirmable
      # t.string   :confirmation_token
      # t.datetime :confirmed_at
      # t.datetime :confirmation_sent_at
      # t.string   :unconfirmed_email # Only if using reconfirmable

      ## Lockable
      # t.integer  :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
      # t.string   :unlock_token # Only if unlock strategy is :email or :both
      # t.datetime :locked_at


      t.timestamps null: false
    end

    add_index :sellers, :email,                unique: true
    add_index :sellers, :reset_password_token, unique: true
    # add_index :sellers, :confirmation_token,   unique: true
    # add_index :sellers, :unlock_token,         unique: true
  end
end
app/models/user.rb

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
end

②Userモデルの編集

app/models/user.rb

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable,
         :confirmable, :lockable, :timeoutable
end

③マイグレーションファイルの編集

db/migrate/20200331113140_devise_create_sellers.rb


class DeviseCreateSellers < ActiveRecord::Migration[5.0]
  def change
    create_table :sellers do |t|
      ## Database authenticatable
      t.string :email,              null: false, default: ""
      t.string :encrypted_password, null: false, default: ""

      ## Recoverable
      t.string   :reset_password_token
      t.datetime :reset_password_sent_at

      ## Rememberable
      t.datetime :remember_created_at

      ## Trackable
      t.integer  :sign_in_count, default: 0, null: false
      t.datetime :current_sign_in_at
      t.datetime :last_sign_in_at
      t.string   :current_sign_in_ip
      t.string   :last_sign_in_ip

      ## Confirmable
      t.string   :confirmation_token
      t.datetime :confirmed_at
      t.datetime :confirmation_sent_at
      t.string   :unconfirmed_email # Only if using reconfirmable

      ## Lockable
      t.integer  :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
      t.string   :unlock_token # Only if unlock strategy is :email or :both
      t.datetime :locked_at


      t.timestamps null: false
    end

    add_index :sellers, :email,                unique: true
    add_index :sellers, :reset_password_token, unique: true
    add_index :sellers, :confirmation_token,   unique: true
    add_index :sellers, :unlock_token,         unique: true
  end
end
$ rails g migration add_columns_to_sellers admin_flag provider uid sellername
db/migrate/20200331114600_add_columns_to_sellers.rb

class AddColumnsToSellers < ActiveRecord::Migration[5.0]
  def change
     change_column :sellers, :admin_flag, :boolean, default: 'false', 
    add_column :sellers, :sellername, :string
  end
end
$ rails db:migrate
== 20200331113140 DeviseCreateSellers: migrating ==============================
-- create_table(:sellers)
   -> 0.0155s
-- add_index(:sellers, :email, {:unique=>true})
   -> 0.0471s
-- add_index(:sellers, :reset_password_token, {:unique=>true})
   -> 0.0201s
-- add_index(:sellers, :confirmation_token, {:unique=>true})
   -> 0.0180s
-- add_index(:sellers, :unlock_token, {:unique=>true})
   -> 0.0342s
== 20200331113140 DeviseCreateSellers: migrated (0.1353s) =====================

== 20200331114600 AddColumnsToSellers: migrating ==============================
-- add_column(:sellers, :admin_flag, :boolean)
   -> 0.0165s
-- add_column(:sellers, :sellername, :string)
   -> 0.0171s
== 20200331114600 AddColumnsToSellers: migrated (0.0709s) =====================

4.viewの編集

app/views/layouts/application.html.erb

<!DOCTYPE html>
<html>
    <head>
        <title>Seller's Pages</title>
        <%= csrf_meta_tags %>

        <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
        <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
    </head>

    <body>
        <header>
            <nav>
                <% if seller_signed_in? %>
                <strong><%= link_to current_seller.sellername, pages_show_path %></strong>
                <%= link_to 'プロフィール変更', edit_seller_registration_path %>
                <%= link_to 'ログアウト', destroy_seller_session_path, method: :delete %>
            <% else %>
                <%= link_to 'サインアップ', new_seller_registration_path %>
                <%= link_to 'ログイン', new_seller_session_path %>
                <% end %>
            </nav>
        </header>

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

        <%= yield %>
    </body>
</html>
app/views/pages/index.html.erb

<h1>ようこそ</h1>
<p>トップページです。</p>
app/views/pages/show.html.erb

<h1>こんにちは、<%= current_seller.sellername %>さん</h1>
<p>ユーザー用ページです。</p>

4.deviseの日本語化

①Gemfileの編集とインストール

以下ファイルにdeviseとomniauth-twitterを追加する。

Gemfile
source 'https://rubygems.org'

(省略)...

# Devise
gem 'devise-i18n'
gem 'devise-i18n-views'

gemをインストールする。

$ bundle install
$rails g devise:views:locale ja

②設定ファイルの変更

devise.views.ja.yml
a:
activerecord:
  errors:
    models:
      seller: # モデル名に合わせる
        attributes:
          email:
            taken: "は既に使用されています。"
            blank: "が入力されていません。"
            too_short: "は%{count}文字以上に設定して下さい。"
            too_long: "は%{count}文字以下に設定して下さい。"
            invalid: "は有効でありません。"
          password:
            taken: "は既に使用されています。"
            blank: "が入力されていません。"
            too_short: "は%{count}文字以上に設定して下さい。"
            too_long: "は%{count}文字以下に設定して下さい。"
            invalid: "は有効でありません。"
            confirmation: "が内容とあっていません。"
  attributes:
    seller: # モデル名に合わせる
      current_password: "現在のパスワード"
      name: 名前
      email: "メールアドレス"
      password: "パスワード"
      password_confirmation: "確認用パスワード"
      remember_me: "次回から自動的にログイン"
  models:
    seller: "取扱者" # モデル名に合わせる
devise:
  confirmations:
    new:
      resend_confirmation_instructions: "アカウント確認メール再送"
  mailer:
    confirmation_instructions:
      action: "アカウント確認"
      greeting: "ようこそ、%{recipient}さん!"
      instruction: "次のリンクでメールアドレスの確認が完了します:"
    reset_password_instructions:
      action: "パスワード変更"
      greeting: "こんにちは、%{recipient}さん!"
      instruction: "誰かがパスワードの再設定を希望しました。次のリンクでパスワードの再設定が出来ます。"
      instruction_2: "あなたが希望したのではないのなら、このメールは無視してください。"
      instruction_3: "上のリンクにアクセスして新しいパスワードを設定するまで、パスワードは変更されません。"
    unlock_instructions:
      action: "アカウントのロック解除"
      greeting: "こんにちは、%{recipient}さん!"
      instruction: "アカウントのロックを解除するには下のリンクをクリックしてください。"
      message: "ログイン失敗が繰り返されたため、アカウントはロックされています。"
  passwords:
    edit:
      change_my_password: "パスワードを変更する"
      change_your_password: "パスワードを変更"
      confirm_new_password: "確認用新しいパスワード"
      new_password: "新しいパスワード"
    new:
      forgot_your_password: "パスワードを忘れましたか?"
      send_me_reset_password_instructions: "パスワードの再設定方法を送信する"
  registrations:
    edit:
      are_you_sure: "本当に良いですか?"
      cancel_my_account: "アカウント削除"
      currently_waiting_confirmation_for_email: "%{email} の確認待ち"
      leave_blank_if_you_don_t_want_to_change_it: "空欄のままなら変更しません"
      title: "%{resource}編集"
      unhappy: "気に入りません"
      update: "更新"
      we_need_your_current_password_to_confirm_your_changes: "変更を反映するには現在のパスワードを入力してください"
    new:
      sign_up: "アカウント登録"
  sessions:
    new:
      sign_in: "ログイン"
  shared:
    links:
      back: "戻る"
      didn_t_receive_confirmation_instructions: "アカウント確認のメールを受け取っていませんか?"
      didn_t_receive_unlock_instructions: "アカウントの凍結解除方法のメールを受け取っていませんか?"
      forgot_your_password: "パスワードを忘れましたか?"
      sign_in: "ログイン"
      sign_in_with_provider: "%{provider}でログイン"
      sign_up: "アカウント登録"
  unlocks:
    new:
      resend_unlock_instructions: "アカウントの凍結解除方法を再送する"

【補足】
『devise.views.ja.yml』ではなくても、『devise.ja.yml』でも日本語化は可能みたい

②設定ファイルの変更2

config/application.rb
equire_relative 'boot'

require 'rails/all'

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

module Ticket2App
  class Application < Rails::Application
    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration should go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded.
    config.i18n.default_locale = :ja # 追記
    config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}').to_s] # 追記
  end
end

③views ファイルの編集

app/views/devise配下の html.erb ファイルの中身を必要に応じて変更する

(一例)

app/views/devise/registration/new.html.erb
<h2>取扱者情報編集</h2>

<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %>
  <%= render "devise/shared/error_messages", resource: resource %>

  <div class="field">
    <%= f.label :sellername, '取扱者' %><br />
    <%= f.text_field :sellername, autofocus: true, autocomplete: "sellername" %>
  </div>

  <div class="field">
    <%= f.label :email, 'メールアドレス' %><br />
    <%= f.email_field :email, autofocus: true, autocomplete: "email" %>
  </div>

  <% if devise_mapping.confirmable? && resource.pending_reconfirmation? %>
    <div>Currently waiting confirmation for: <%= resource.unconfirmed_email %></div>
  <% end %>

  <div class="field">
    <%= f.label :password, '新しいパスワード'%> <i>(leave blank if you don't want to change it)</i><br />
    <%= f.password_field :password, autocomplete: "new-password" %>
    <% if @minimum_password_length %>
      <br />
      <em><%= @minimum_password_length %> characters minimum</em>
    <% end %>
  </div>

  <div class="field">
    <%= f.label :password_confirmation, 'パスワード(確認用)' %><br />
    <%= f.password_field :password_confirmation, autocomplete: "new-password" %>
  </div>

  <div class="field">
    <%= f.label :current_password, '現在のパスワード' %> <i>(we need your current password to confirm your changes)</i><br />
    <%= f.password_field :current_password, autocomplete: "current-password" %>
  </div>

  <div class="actions">
    <%= f.submit "更新" %>
  </div>
<% end %>

<h3>更新をキャンセル</h3>

<%= button_to "更新をキャンセル", registration_path(resource_name), data: { confirm: "本当によろしいですか?" }, method: :delete %>

</br>

<%= link_to "戻る", :back %>
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0