1. 程式人生 > >rails 實現登入和註冊功能

rails 實現登入和註冊功能

思路:使用者註冊需要user這個model, user控制器控制使用者的註冊功能,session控制器控制使用者的登入功能,welcome控制器控制使用者登入和退出的跳轉,為了表單友好,增加bootstrap樣式

生成User model
rails g model user


修改db/migrate生成的檔案
class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
    t.string :username
    t.string :password
      t.timestamps null: false
    end
  end
end


遷移檔案
rake db:migrate

模型驗證

class User < ActiveRecord::Base

  validates :username, presence: { message: "使用者名稱不能為空" }
  validates :username, uniqueness: { message: "使用者名稱已存在" }
  validates :password, presence: { message: "密碼不能為空" }
  validates :password, length: { minimum: 6, message: "密碼長度最短為6位" }

end

生成控制器
rails g controller users
rails g controller sessions
rails g controller welcome


生成對應的路由
resources :users
resources :sessions
root "welcome#index"


生成登錄檔單

views/users/new.html.erb

<h1>使用者註冊</h1>
<div class="row">
  <div class="col-sm-5">
    <%= form_for @user, url: users_path, method: :post do |f| %>
      <div class="form-group">
        <ul class="list-unstyled">
          <% @user.errors.messages.values.flatten.each do |error| %>
            <li><i class="fa fa-exclamation-circle"></i> <%= error %></li>
          <% end -%>
        </ul>
      </div>
      <div class="form-group">
        <%= f.text_field :username, class: "form-control", placeholder: "使用者名稱" %>
      </div>
      <div class="form-group">
        <%= f.password_field :password, class: "form-control", placeholder: "密碼" %>
      </div>
      <%= f.submit "註冊", class: "btn btn-primary" %> 
      <%= link_to "登入", new_session_path %>
    <% end -%>
  </div>
  <div class="col-sm-7">
  </div>
</div>


user_controller.rb

class UsersController < ApplicationController

def new
@user = User.new
end

def create
@user = User.new(params.require(:user).permit(:username, :password))
if @user.save
flash[:notice] = '註冊成功,請登入'
redirect_to new_session_path
else
render action: :new
end
end

end


生成登入表單

views/sessions/new.html.erb

<h1>使用者登入</h1>
<div class="row">
  <div class="col-sm-4">
    <%= form_tag sessions_path, method: "post" do %>
      <div class="form-group">
        <input type="text" name="username" placeholder="使用者名稱..." class="form-control" id="form_username" title="使用者名稱6-12個字元">
      </div>
      <div class="form-group">
        <input type="password" name="password" placeholder="密碼..." class="form-control" id="form_password">
      </div>
      <input type="submit" class="btn btn-primary" value="登入" /> 
      <%= link_to "註冊", new_user_path %>
    <% end %>
  </div>
  <div class="col-sm-8">
  </div>
</div>


sessions_controller.rb


class SessionsController < ApplicationController

def create
@user = User.find_by(username: params[:username], password: params[:password])
if @user
session[:user_id] = @user.id
flash[:notice] = '登入成功'
redirect_to root_path
else
flash[:notice] = "使用者名稱或者密碼不正確" 
render action: :new
end
end

def destroy
session[:user_id] = nil
flash[:notice] = "退出成功"
redirect_to root_path
end

end


首頁表單

views/welcome/index.html.erb

<% if @user %>
  <h1>歡迎你, <%= @user.username %></h1>
<% else %>
  <h1>Circles 首頁</h1> 
<% end -%>

修改layouts/application.html.erb 檔案

<!DOCTYPE html>
<html>
  <head>
    <title>Circles</title>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    
    <%= stylesheet_link_tag    'application', media: 'all' %>
    <%= javascript_include_tag 'application' %>
    <%= csrf_meta_tags %>
  </head>
  <body>
    <header name="top">
      <nav class="navbar navbar-default navbar-fixed-top nav-color" role="navigation" id="nav">
        <div class="container">
          <!-- Brand and toggle get grouped for better mobile display -->
          <div class="navbar-header nav-color">
            <button id="nav_collapse" type="button" class="navbar-toggle toggle-btn" data-toggle="collapse" data-target="#bs-navbar-collapse-1" aria-controls="bs-navbar-collapse-1">
              <span class="fa fa-bars fa-lg"></span>
            </button>
            <a class="navbar-brand custom-logo-link" href="/">
              Circles
            </a>
          </div>

          <!-- Collect the nav links, forms, and other content for toggling -->
          <div class="collapse navbar-collapse nav-submenu-color collapse" id="bs-navbar-collapse-1">
            <ul class="nav navbar-nav navbar-right custom">
              <li>
                <a href="/">Home</a>
              </li>

              <% if session[:user_id] %>
                <li><%= link_to "#{User.find_by(session[:user_id]).username}, 退出", session_path(session[:user_id]), method: 'delete' %></li>
              <% else %>
                <li><%= link_to "登入", new_session_path %></li>
              <% end -%>
            </ul>
          </div>
          <!-- /.navbar-collapse -->
        </div>
        <!-- /.container-->
      </nav>
    </header>


    <div class="container body-offset">
      <% if flash[:notice] %>
        <div class="alert alert-info"><%= flash[:notice] %></div>
      <% end -%>
      
      <%= yield %>
    </div>
  </body>
</html>