blue workbench

Ruby and Rails

【Rails】deviseを導入する

必ずやる手順

gem 'devise'
$ bundle install
$ rails generate devise:install
Running via Spring preloader in process 74332
      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

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

config/environments/development.rb

config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
$ rails g devise user
Running via Spring preloader in process 78768
      invoke  active_record
      create    db/migrate/20200619145340_devise_create_users.rb
      create    app/models/user.rb
      invoke    rspec
      create      spec/models/user_spec.rb
      invoke      factory_bot
      create        spec/factories/users.rb
      insert    app/models/user.rb
       route  devise_for :users

t.string :screen_name, null: false を追加したり、一部コメントインしました。 db/migrate/20200619145340_devise_create_users.rb

# frozen_string_literal: true

class DeviseCreateUsers < ActiveRecord::Migration[6.0]
  def change
    create_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

      ## add columns
      t.string :screen_name, null: false


      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
end
$ rails db:migrate
== 20200619145340 DeviseCreateUsers: migrating ================================
-- create_table(:users)
   -> 0.0864s
-- add_index(:users, :email, {:unique=>true})
   -> 0.0133s
-- add_index(:users, :reset_password_token, {:unique=>true})
   -> 0.0046s
-- add_index(:users, :confirmation_token, {:unique=>true})
   -> 0.0028s
== 20200619145340 DeviseCreateUsers: migrated (0.1073s) =======================

app/models/user.rb

# frozen_string_literal: true

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

【Rails】マイグレーションまとめ

テーブル作成

# frozen_string_literal: true

class CreateProducts < ActiveRecord::Migration[6.0]
  def change
    create_table :products do |t|
      # NOT NULL制約
      t.string :name, null: false
      t.integer :price, null: false

      t.timestamps
    end
  end
end

複数カラムのユニーク制約追加

$ rails g migration AddUniquenessToCartDetails

db/migrate/20200629130430_add_uniqueness_to_cart_details.rb

class AddUniquenessToCartDetails < ActiveRecord::Migration[6.0]
  def change
  end
end
# frozen_string_literal: true

class AddUniquenessToCartDetails < ActiveRecord::Migration[6.0]
  def change
    add_index :cart_details, %i[cart_id product_id], unique: true
  end
end

参考

yamakichi.hatenablog.com

【Rails】バリデーションまとめ

# frozen_string_literal: true

class User < ApplicationRecord
  validates :screen_name,
            # 必須
            presence: true,
            # 長さ
            length: { maximum: 20 },
            # 一意制約(大文字小文字区別しない)
            uniqueness: { case_sensitive: false }
end
# frozen_string_literal: true

class Product < ApplicationRecord
  # 必須
  validates :name,
            :price,
            presence: true

  # 数値(しかも整数のみOK)
  validates :price, numericality: { only_integer: true }
end

参考

railsguides.jp

【RubyMine】設定のカスタマイズまとめ

適宜追記していきます。

保存系

  • カーソルが外れると自動保存されること(確かデフォルトでそうだったはず)
  • 一定時間経過で自動保存されること(秒数も指定できるので、1secにしてる)
  • 保存時にファイル末尾が改行されること
  • 保存時に行末の空白が除去されること→使いづらかったのでやめました。

コードフォーマット系

  • Curly braces in hashes にチェック

【Rails】railsコマンドまとめ

適宜更新です。

rails db:xxxxx

root@1f4605d9b6ff:/workspace# rails db:drop
Dropped database 'rails_docker_development'
Dropped database 'rails_docker_test'
root@1f4605d9b6ff:/workspace# rails db:create
Created database 'rails_docker_development'
Created database 'rails_docker_test'