##前提
- macOS mojave 10.14.3
- rails 5.1
- 環境環境 local
- Bootstrap、secure_password 導入後
###テーブル
schema.rb
ActiveRecord::Schema.define(version: 20190318144456) do
create_table "users", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8" do |t|
t.string "name"
t.string "email"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "image_name"
t.string "password_digest"
end
###ルート
routes.rb
Rails.application.routes.draw do
post 'login', to:'users#login'
post 'users/create', to:'users#create'
end
###コントローラー
users_controller.rb
def create
@user = User.new(
name: params[:name],
email: params[:email],
image_name:"default_user.jpg",
password: params[:password]
)
if @user.save
session[:user_id] = @user.id
flash[:notice] = "User registration has been completed."
@current_user = @user
redirect_to("/users/#{@user.id}")
else
render("users/new")
end
end
def login
@user = User.find_by(email: params[:email])
if @user && @user.authenticate(params[:password])
session[:user_id] = @user.id
flash[:notice] = "Logged in"
redirect_to("/posts/index")
else
@error_message = "Your email or username is incorrect."
@email = params[:email]
@password = params[:password]
render("users/login_form")
end
end
###ユーザー登録フォーム
<%= form_with url: users_create_path, local: true do |form| %>
new.html.erb
<h1>Sign Up</h1>
<p>Please fill in this form to create an account.</p>
<%= form_with url: users_create_path, local: true do |form| %>
<%= form.label :name %>
<li>
<%= form.text_field :name %>
</li>
<%= form.label :email %>
<li>
<%= form.email_field :email %>
</li>
<%= form.label :password %>
<li>
<%= form.password_field :password %>
</li>
<%= form.label :password_confirmation, "Confirmation" %>
<li>
<%= form.password_field :password_confirmation %>
</li>
<%= form.submit "Create my account", class: "btn btn-primary" %>
<% end %>
###ログインフォーム
<%= form_with url:login_path, local: true do |form| %>
login_form.html.erb
<h1>Log in</h1>
<p>Please fill in this form to log in.</p>
<%= form_with url:login_path, local: true do |form| %>
<%= form.label :name %>
<li>
<%= form.text_field :name %>
</li>
<%= form.label :email %>
<li>
<%= form.email_field :email %>
</li>
<%= form.label :password %>
<li>
<%= form.password_field :password %>
</li>
<%= form.label :password_confirmation, "Confirmation" %>
<li>
<%= form.password_field :password_confirmation %>
</li>
<%= form.submit "Log in", class: "btn btn-primary" %>
<% end %>
###参考資料
[Rails 5.1] ‘form_with’ APIドキュメント完全翻訳 https://techracho.bpsinc.jp/hachi8833/2017_05_01/39502