Implement it more simply than the email and password login used in the rails tutorial. Do not use gems such as devise.
Here, log in using the name and password of the Room table.
MacBook % rails g model Room name:string
db/migrate/Time stamp.create_rooms.rb
class CreateRooms < ActiveRecord::Migration[6.0]
def change
create_table :rooms do |t|
t.string :name, null: false
t.timestamps
end
end
end
MacBook % rails db:migrate
app/models/room.rb
class Room < ApplicationRecord
validates :name, presence: true, length: { maximum: 50 }
has_secure_password
end
--Create a migration to add the password_digest column and apply the migration
MacBook % rails generate migration add_password_digest_to_rooms password_digest:string
MacBook % rails db:migrate
--Open Gemfile, uncomment gem'bcrypt' and install
Gemfile
~
# gem 'redis', '~> 4.0'
# Use Active Model has_secure_password
gem 'bcrypt', '~> 3.1.7'
# Use Active Storage variant
# gem 'image_processing', '~> 1.2'
~
--Additionally limit empty password and minimum number of characters
app/models/room.rb
class Room < ApplicationRecord
validates :name, presence: true, length: { maximum: 50 }
has_secure_password
validates :password, presence: true, length: { minimum: 6 }
end
--Check if the instance can be created and saved in the database with Rails console
A terminal different from the one that started the server
MacBook % rails c
~
irb(main):001:0> @room = Room.new(name:"tokyoroom",password:"password",password_confirmation:"password")
(2.2ms) SET NAMES utf8mb4, @@SESSION.sql_mode = CONCAT(CONCAT(@@sql_mode, ',STRICT_ALL_TABLES'), ',NO_AUTO_VALUE_ON_ZERO'), @@SESSION.sql_auto_is_null = 0, @@SESSION.wait_timeout = 2147483
=> #<Room id: nil, name: "tokyoroom", created_at: nil, updated_at: nil, password_digest: [FILTERED]>
irb(main):002:0> @room.save
(0.7ms) BEGIN
Room Create (3.3ms) INSERT INTO `rooms` (`name`, `created_at`, `updated_at`, `password_digest`) VALUES ('tokyoroom', '2020-09-23 07:26:30.787094', '2020-09-23 07:26:30.787094', '$2a$12$SmCtpmRZn0M5BMtuT6BmAOKO.DMAmMOIYSXoHlxDrSbA2AQcAYnMC')
(5.0ms) COMMIT
=> true
(https://qiita.com/yongjugithub/items/65fcdf73e42857297321)
https://railstutorial.jp/chapters/modeling_users?version=5.1#sec-adding_a_secure_password
Recommended Posts