思路:用户注册需要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
用户注册
<%= form_for @user, url: users_path, method: :post do |f| %>
<%= f.text_field :username, class: "form-control", placeholder: "用户名" %>
<%= f.password_field :password, class: "form-control", placeholder: "密码" %>
<%= f.submit "注册", class: "btn btn-primary" %>
<%= link_to "登录", new_session_path %>
<% end -%>
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
用户登录
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 %>
欢迎你, <%= @user.username %>
<% else %>
Circles 首页
<% end -%>
修改layouts/application.html.erb 文件
Circles <%= stylesheet_link_tag 'application', media: 'all' %>
<%= javascript_include_tag 'application' %>
<%= csrf_meta_tags %>
<% if flash[:notice] %>
<%= flash[:notice] %>
<% end -%>
<%= yield %>