LoginSignup
0
0

投稿アプリ ユーザー管理機能実装

Posted at

学習を進めていく中で、理解できたと思っていた部分が自力でやろうとするとまだまだだということが分かったので、ここで再度アウトプットします。

deviseを使ったユーザー管理機能の実装手順です。

deviseの導入・userモデル作成

deviseを使った場合、コマンドはrails g deviseになる。

Gemfile
gem 'devise'
% rails g devise:install
% rails s
% rails g devise user

マイグレーションファイルにカラムの追加。

deviseを使うとemail.passwordは自動で生成される。

_create_user.rb
t.string :name
t.text :profile
% rails db:migrate

バリデーションの設定。

空欄では保存できないことを定義。

user.rb
validates :name, presence: true
validates :profile, presence: true
validates :position, presence: true

ビューファイル。

modelには@モデル名、rulはdevise/registrations#newに対応するパス。
registrationは新規登録。
※対してsessionはログイン。

new.html.erb
<%= form_with model: @user, url: user_registration_path, local: true do |f| %> 

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

<div class="field">
  <%= f.label :password, "パスワード(6文字以上)" %><br />
  <%= f.password_field :password, id:"user_password", autocomplete: "new-password" %>
</div>

<div class="field">
  <%= f.label :password_confirmation, "パスワード再入力" %><br />
  <%= f.password_field :password_confirmation, id:"user_password_confirmation", autocomplete: "new-password" %>
 </div>

<div class="field">
  <%= f.label :name, "ユーザー名" %><br />
  <%= f.text_field :name, id:"user_name" %>
</div>

<div class="field">
  <%= f.label :profile, "プロフィール" %><br />
  <%= f.text_area :profile, class: :form__text, id:"user_profile" %>
</div>

<div class="actions">
  <%= f.submit "新規登録", class: :form__btn  %>
</div>
<% end %>

追加したカラムの情報を取得できるようにする

application_controller.rb
class ApplicationController < ActionController::Base
  before_action :configure_permitted_parameters, if: :devise_controller?

  private
  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:name, :position])
  end 
end
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