devise 배포에서 사용자의 프로필 화면을 만들 때까지
소개
devise로 만든 user 테이블에 이름이나 프로필을 넣어 두고 싶었기 때문에 해 보았습니다.
스스로 로그인 기능을 만들면 간단하게 할 수 있습니다만, devise를 괴롭히는 것은 처음에는 용기가 있다고 생각하기 때문에 그런 분들의 도움이 된다고 써 봅니다.
여기에서는 가입 시 이름을 입력할 수 있도록 하고 계정을 편집할 때 이름과 프로필을 입력할 수 있도록 해 봅니다.
버전
Ruby 2.3.1
Rails 5.1.6
devise 4.5.0
다양한 설치
우선, 견본이라고 하는 것으로 여기에서는 적당하게 블로그 어플리를 만듭니다.
$ rails new devise_app
$ rails g scaffold blog title:string content:text
$ rails db:create
$ rails db:migrate
그런 다음 devise를 설치합니다.
gem 'devise'
덧붙여서 이와 같이 버전을 지정하지 않는 쓰는 방법이라고 자동적으로 최신판이 인스톨 됩니다.
$ bundle install
이 후에
$ rails g devise:install
이것으로 devise 설치 완료입니다.
devise의 각종 파일을 준비
모델 생성
$ rails g devise user
이제 모델과 마이그레이션 파일을 만들 수 있습니다.
view 생성
$ rails g devise:views
그러면 이와 같이 devise에서 사용되는 view 파일이 작성됩니다.

덧붙여서 이중에서 이번 사용하는 것은 registrationss 뿐입니다.
controller 생성
$ rails g devise:controllers users
controller도 몇 가지가 있습니다만 이번 devise 관련의 기술을 실시하는 것은 registrations_controller.rb와 apprication_controller.rb입니다.

다양한 파일 편집
마이그레이션 파일
이번에는 프로필 화면에 사용자의 이름과 프로필을 표시하고 싶으므로 name과 profile의 열을 추가합니다.
db/migrate/〇〇_devise_create_users.rb
# frozen_string_literal: true
class DeviseCreateUsers < ActiveRecord::Migration[5.1]
def change
create_table :users do |t|
t.string :name, null: false #追記
t.text :profile #追記
## Database authenticatable
t.string :email, null: false, default: ""
t.string :encrypted_password, null: false, default: ""
"rails db:migrate"를 잊지 마세요.
모델
app/models/user.rb
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
validates :name, presence: true #追記
validates :profile, length: { maximum: 200 } #追記
end
name 과 profile 에 밸리데이션을 걸어 둡니다.
컨트롤러
app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
# ログイン済ユーザーのみにアクセスを許可する
before_action :authenticate_user!
# deviseコントローラーにストロングパラメータを追加する
before_action :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
# サインアップ時にnameのストロングパラメータを追加
devise_parameter_sanitizer.permit(:sign_up, keys: [:name])
# アカウント編集の時にnameとprofileのストロングパラメータを追加
devise_parameter_sanitizer.permit(:account_update, keys: [:name, :profile])
end
end
이제 사용자 모델에 추가한 매개변수를 전달할 수 있습니다.
덧붙여서 application_controller.rb에 「:authenticate_user!」를 설정하고 있으므로 어떤 페이지에서도 로그인하지 않으면 로그인 페이지로 날아가게됩니다.
보기
app/views/devise/registrations/new.html.erb
<h2>Sign up</h2>
<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
<%= devise_error_messages! %>
<!--サインアップ時に名前を入力できるようにフォームを追加-->
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name, autofocus: true %>
</div>
<div class="field">
<%= f.label :email %><br />
<%= f.email_field :email, autofocus: true, autocomplete: "email" %>
</div>
app/views/devise/registrations/edit.html.erb
<h2>Edit <%= resource_name.to_s.humanize %></h2>
<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %>
<%= devise_error_messages! %>
<!--アカウント編集時に名前を入力できるようにフォームを追加-->
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name, autofocus: true %>
</div>
<div class="field">
<%= f.label :email %><br />
<%= f.email_field :email, autofocus: true, autocomplete: "email" %>
</div>
<!--アカウント編集時にプロフィールを入力できるようにフォームを追加-->
<div class="field">
<%= f.label :profile %><br />
<%= f.text_area :profile, autofocus: true %>
</div>
각 뷰에 입력 양식을 추가합니다.
이제 가입 시 이름, 계정 편집에서 이름과 프로필을 입력할 수 있습니다.


사용자 프로필 화면 만들기
라우팅
config/routes.rb
resources :users, only: [:show]
# ログイン、アカウント編集後、任意のページに推移させるための記述
devise_for :users, controllers: {
registrations: 'users/registrations'
}
사용자의 show로 라우팅 만들기
그 아래의 "devise_for"에 관해서는 registrations_controller.rb로 기술하는 내용을 유효하게 하기 위해서입니다.
컨트롤러
app/controllers/users/registrations_controller.rb
protected
# アカウント編集後、プロフィール画面に移動する
def after_update_path_for(resource)
user_path(id: current_user.id)
end
app/controllers/users/apprication_controller.rb
# ログイン後、blogs/indexに移動する
def after_sign_in_path_for(resource)
blogs_path
end
devise 설정은 여기서 끝납니다.
그리고는 프로필 화면을 작성해 갑니다.
$ rails g controller Users show
devise의 users와는 별도로 users_controller.rb와 users/show.html.erb를 생성합니다.
app/controllers/users_controller.rb
class UsersController < ApplicationController
def show
@user = User.find(params[:id]) #追記
end
end
보기
app/views/users/show.html.erb
<h1>Users#show</h1>
<p>名前 : <%= @user.name %></p>
<p>メールアドレス : <%= @user.email %></p>
<p>プロフィール : <%= @user.profile %></p>
우선 표시하는 것만

끝에
devise를 처음 사용했을 때 편리하다고 생각한 반면, 사용하지 않는 파일이 많이 생성되기 때문에 엉망이 되어 커스터마이즈하기 어려운 인상이었습니다.
실제로 스스로 놀 때 상당한 용기가 필요했습니다.
이 기사가 devise를 커스터마이즈 하는 분에게 있어서, 처음의 한 걸음의 도움이 되면 다행입니다.
또, 의견이나 지적, 질문등도 대환영입니다!
Reference
이 문제에 관하여(devise 배포에서 사용자의 프로필 화면을 만들 때까지), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/ryokky59/items/71b5a853989721b89c6e텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)