プロダクト開発日誌

技術のことなど

【Rails】1対多のリレーションを作成

Zoneモデルを作成し、AreaモデルとZoneモデルを1対多のリレーションを作成します。

Zoneモデルの作成

bin/rails g scaffold Zone name:string description:text

Migration File

class CreateZones < ActiveRecord::Migration[6.0]
  def change
    create_table :zones do |t|
      t.string :name, null: false, unique: true
      t.text :description

      t.timestamps
    end
  end
end

Migration

bin/rails db:migrate
bundle exec annotate

1対多のRelation

bin/rails g migration add_area_ref_to_zones area:references
class AddAreaRefToZones < ActiveRecord::Migration[6.0]
  def change
    add_reference :zones, :area, foreign_key: true
  end
end
bin/rails db:migrate
bundle exec annotate

models/zone.rb

belongs_to :area

models/area.rb

has_many :zones

画像アップロード機能を追加(Active Storage)

ユーザモデルに画像を追加します。

bin/rails active_storage:install

マイグレーションファイルを確認

class CreateActiveStorageTables < ActiveRecord::Migration[5.2]
  def change
    create_table :active_storage_blobs do |t|
      t.string   :key,        null: false
      t.string   :filename,   null: false
      t.string   :content_type
      t.text     :metadata
      t.bigint   :byte_size,  null: false
      t.string   :checksum,   null: false
      t.datetime :created_at, null: false

      t.index [ :key ], unique: true
    end

    create_table :active_storage_attachments do |t|
      t.string     :name,     null: false
      t.references :record,   null: false, polymorphic: true, index: false
      t.references :blob,     null: false

      t.datetime :created_at, null: false

      t.index [ :record_type, :record_id, :name, :blob_id ], name: "index_active_storage_attachments_uniqueness", unique: true
      t.foreign_key :active_storage_blobs, column: :blob_id
    end
  end
end

マイグレーション

bin/rails db:migrate

config/environments/development.rb

# Store uploaded files on the local file system (see config/storage.yml for options).
config.active_storage.service = :local

config/storage.yml

# 何処に画像を保存するかの設定

Userモデルに画像を添付できるようにする

class User < ApplicationRecord
  has_one_attached :image
end

User controllerの作成

bin/rails generate devise:controllers users

route.rb

Rails.application.routes.draw do
  devise_for :users, controllers: {
    registrations: 'users/registrations'
  }
  root to: 'areas#index'
  resources :areas
  # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end

app/controllers/users/registrations_controller.rb

# frozen_string_literal: true

class Users::RegistrationsController < Devise::RegistrationsController
  before_action :configure_sign_up_params, only: [:create]
  before_action :configure_account_update_params, only: [:update]


  # protected

  # If you have extra params to permit, append them to the sanitizer.
  def configure_sign_up_params
    devise_parameter_sanitizer.permit(:sign_up, keys: [:image])
  end

  # If you have extra params to permit, append them to the sanitizer.
  def configure_account_update_params
    devise_parameter_sanitizer.permit(:account_update, keys: [:image])
  end

end

画面の設定

app/views/devise/registrations/new.html.slim app/views/devise/registrations/edit.html.slim

.field
    = f.label :image
    br
    = f.file_field :image

Railsにユーザ認証機能を追加(devise)

install

# Flexible authentication solution for Rails with Warden.
gem 'devise'
bundle install
bin/rails g devise:install

config/initializers/devise.eb ・・・ Deviseの設定を行うファイル config/locals/devise.en.yml ・・・ Deviseのローカライゼーション用ファイル

config/environments/development.rb

config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }

root urlを指定: config/routes.rb

root to: "home#index"

Flash Messageを追加: app/views/layouts/application.html.slim

p.notice= notice
p.alert= alert

View Fileを作成

bin/rails g devise:views

secret_keyの発行?

bin/rails secret
f63f6ce0e65208abe21abeaa8d3db687836e850771d740b9e21ce4fd7960b97b640be6c45d92d8d10b9c4f681a4e4a0717928035d42d671073f7682a920057b8

Deviseに紐付いたモデルの作成

bin/rails g devise user

Deviceの利用するモジュールを指定: app/models/user.rb

class User < ApplicationRecord
  devise :database_authenticatable,
         :registerable,
         :recoverable,
         :rememberable,
         :validatable,
         :confirmable,
         :lockable,
         :timeoutable,
         :omniauthable
end

MigrationFileを変更:

# frozen_string_literal: true

class AddDeviseToUsers < ActiveRecord::Migration[6.0]
  def self.up
    change_table :users 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.inet     :current_sign_in_ip
      t.inet     :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

      # Uncomment below if timestamps were not included in your original model.
      # t.timestamps null: false
    end

    add_index :users, :email,                unique: true
    add_index :users, :reset_password_token, unique: true
    add_index :users, :confirmation_token,   unique: true
    add_index :users, :unlock_token,         unique: true
  end

  def self.down
    # By default, we don't want to make any assumption about how to roll back a migration when your
    # model already existed. Please edit below which fields you would like to remove in this migration.
    raise ActiveRecord::IrreversibleMigration
  end
end

Migration

bundle exec rails db:migrate

Annotate

bundle exec annotate

erbをslimに追加

bundle exec erb2slim app/views/devise/ --delete

RailsのER図を書き出すgem

voormedia.github.io

rails-erdを利用するには Graphviz が必要です http://graphviz.org/

sudo port install graphviz

Gem をインストール

group :development do
  # Generate Entity-Relationship Diagrams for Rails applications. Read more: http://voormedia.github.io/rails-erd/
  gem "rails-erd"
end
bundle install

ER図を作成

bundle exec erd

Git hooksの導入

github.com

git hooksはコミットやマージの前にスクリプトを走らす機能

Hooksの運用に便利なgem overcommitをインストールする

group :development do
  # A fully configurable and extendable Git hook manager
  # Read more: https://github.com/brigade/overcommit
  gem 'overcommit'
end
bundle install
bundle exec overcommit --install

設定

.overcommit.yml

PreCommit:
  AuthorName:
    enabled: false
  Annotate:
    enabled: ture
    command: ['bundle', 'exec', 'annotate'] # Invoke within Bundler context
  RuboCop:
    enabled: ture
    command: ['bundle', 'exec', 'rubocop']

設定変更を反映

bundle exec overcommit -s

現在の設定を確認

bundle exec overcommit -l

Rails app に Rubocopを導入する

github.com

Gemfile

group :development do
  # A Ruby static code analyzer and formatter, based on the community Ruby style guide. https://docs.rubocop.org
  gem 'rubocop', require: false
end
bundle install

touch .rubocop.yml

AllCops:
  Rails: true

  Exclude:
  - bin/**/*
  - config/environments/**/*
  - config/initializers/**/*
  - config/application.rb
  - config/puma.rb
  - config/spring.rb
  - db/schema.rb
  - db/migrate/**/*
  - db/seeds.rb
  - lib/tasks/**/*
  - public/**/*
  - node_modules/**/*
  - vendor/**/*


# "Missing top-level class documentation comment."を無効
Style/Documentation:
  Enabled: false

LineLength:
  Max: 120

使い方

bundle exec rubocop

自動修正

bundle exec rubocop --auto-correct