15. 회원가입 기능 구현

2020. 6. 30. 16:14Rails 5 on aws c9

15. 회원가입 기능 구현

회원가입을 하기 위해 Users 컨트롤러를 만들어야 함

회원가입 폼은 new에서 만들겠다.

ubuntu:~/environment/hello_world (master) $ rails g controller Users new

Running via Spring preloader in process 1517
      create  app/controllers/users_controller.rb
       route  get 'users/new'
      invoke  erb
      create    app/views/users
      create    app/views/users/new.html.erb
      invoke  test_unit
      create    test/controllers/users_controller_test.rb
      invoke  helper
      create    app/helpers/users_helper.rb
      invoke    test_unit
      invoke  assets
      invoke    coffee
      create      app/assets/javascripts/users.coffee
      invoke    scss
      create      app/assets/stylesheets/users.scss

config에 route파일을 열어서 자동생성된 라우트 규칙을 지워주고

리소스를 추가해준다.

Rails.application.routes.draw do

  # get 'users/new' 자동생성된 라우트 규직 삭제

  #지금은 쓰고싶은 액션이 3개 뿐이다.
  resources :contacts, only: [:index, :create, :new] 
  #리소스 이용해서 유저라우트 규칙 생성
  resources :users, onlt: [:new, :create]

    get '/' => 'home#hello_world' 
    get '/index' => 'home#index'
    get '/contact' => 'home#contact'
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end

domain/users/new로 들어가면 다음과 같이 나오는걸 볼 수 있다.

 

console에서 routes규칙을 찾아보자

ubuntu:~/environment/hello_world (master) $ rake routes

     Prefix Verb URI Pattern             Controller#Action
   contacts GET  /contacts(.:format)     contacts#index
            POST /contacts(.:format)     contacts#create
new_contact GET  /contacts/new(.:format) contacts#new
      ***users POST /users(.:format)        users#create
   new_user GET  /users/new(.:format)    users#new***
            GET  /                       home#hello_world
      index GET  /index(.:format)        home#index
    contact GET  /contact(.:format)      home#contact

application.html.erb 에서 contact 코드를 복사한 뒤 약간 수정해주자.

<!DOCTYPE html>
<html>
  <head>
    <title>HelloWorld</title>
    <%= csrf_meta_tags %>

    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
  </head>

  <body>
    <div id="global-header">
      <div class="container">
        <div class="logo">My Profile</div>
        <ul class="menu">
          <a href="/">
            <li class="item">Hello World</li>
          </a>
          <!--link_to 헬퍼를 이용 해보자-->
          <!--<a href="/contacts/new">-->
          <%= link_to new_contact_path do %>
            <li class="item">Contact</li>
          <!--</a>-->
          <% end %>

          ***<%= link_to new_user_path do %>
            <li class="item">Sign up</li>
          <% end %>***

        </ul>
      </div>
    </div>

    <%= yield %>
  </body>
</html>

새로고침해보면 이렇게 sign up 페이지가 생겼다.

그럼 이제 sign up 폼을 만들어보자.

views/users/new.html.erb 에 들어가서 다음을 작성해주자.

<h1>Sign up</h1>
<%= form_tag users_path do %>
    Email :
    <input type="email" name="email"><br>
    Password :
    <input type="password" name="password"><br>
    Password Confirmation :
    <input type="password" name="password_confirmation"><br>
    Name :
    <input type="text" name="name"><br>
    <input type="submit" value="Sign up">

<% end %>

그럼 다음과같은 폼이 나온다.

값을 넣어서 sign up을 누르면, create 액션이 없다고 나온다.

controllers/users_controller.rb

class UsersController < ApplicationController
  def new
  end

  def create
    User.create(email: params[:email],
                password: params[:password],
                password_confirmation: params[:password_confirmation],
                name: params[:name])
    redirect_to '/'
  end
end

하고 Sign_up을 실행하면 잘 작동한다 (혹시 cannot load such file -- bcrypt 에러가 뜬다면, 서버를 ctrl+c해서 종료하고, rails s 명령어를 다시 시작해 서버를 재시작 한 뒤 시도해보길 바란다.)

가입되었는지 확인하기위해서는 콘솔에서 User.all하면 볼 수 있다.

ubuntu:~/environment/hello_world (master) $ rails c

Running via Spring preloader in process 2102
ULoading development environment (Rails 5.0.7.2)

2.6.3 :001 > User.all
  User Load (1.1ms)  SELECT "users".* FROM "users"
 => #<ActiveRecord::Relation [#<User id: 1, name: "hs", email: "hs@naver.com", password_digest: "$2a$12$y3C8lNSaK9EfUvSgziUDtuyC5xp4DpgrnpxgZCde/kk...", created_at: "2020-06-11 07:56:26", updated_at: "2020-06-11 07:56:26">]> 

2.6.3 :002 >