LoginSignup
1
0

More than 5 years have passed since last update.

ユーザー登録機能つき投稿サイト⓷(ユーザー作成とポストのアソシエーション)

Posted at

1、deviseを用いた新規ユーザー登録の際に、emailとpassword以外にも,userの名前を登録できるようにする。
つまり、userテーブルにnameカラムを追加し、nameも登録できるようにする。

qiita.rb
rails g migration add_name_to_user name:string
rails db:migrate

2,deviseの指示である、rails g devise:viewsでuser登録に関するviewを生成。
devise/registrations/new.html.erbとedit.html.erbの中のform部分を以下に変更し、nameも登録できるようにする。

new.html.erb(新規ユーザー登録)
<div class="field">
    <%= f.label :name %><br /> ←これを追加
        <%= f.text_field :name, autofocus: true, autocomplete: "name" %><br />←これを追加
    <%= f.label :email %><br /> 
    <%= f.email_field :email, autofocus: true, autocomplete: "email" %>
</div>
edit.html.erb(既存ユーザーの編集)
<div class="field">
    <%= f.label :name %><br /> ←これを追加
    <%= f.text_field :name, autofocus: true, autocomplete: "name" %><br /> ←これを追加
    <%= f.label :email %><br />
    <%= f.email_field :email, autofocus: true, autocomplete: "email" %>
</div>

3,nameを受け取るためには、「ストロングパラメーター」にnameも追加しなくてはならない。
/controllers/application_controller.rbに以下を追加。
permit(:sign_up, keys: [:許可したいカラム名])の形

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

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:name])
  end
end

4,これでuser.nameを保存できるようになった。posts/show.html.erbに以下を追加。
(postを投稿したuserのnameとidを参照する)

qiita.rb

<h1>name of editer:<%= @post.user.name %></h1>
<h1>user_No.<%= @post.user.id %>
1
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
1
0