准备工具
ruby v2.2.6
rails v5.0.0.1
开整
- 新建项目
rails new blog
- 进入目录
cd blog
- 在Gemfile添加
gem "rails-i18n" #用于本地化
gem "slim-rails" #使用slim代替erb模板
gem "bcrypt" #用于密码的校验(不可少)
- 再
bundle install
- 创建用户注册model
rails g model User name password password_digest
[1]
#app/models/user.rb
class User < ActiveRecord::Base
+ has_secure_password #用于密码的校验
end
- 创建控制器
rails g controller user new index new create
#app/controllers/users_controller.rb
class UserController < ApplicationController
def new
@user=User.new
end
def index
end
def create
@user=User.create(user_params)
if @user.save
redirect_to :sessions_new #用户信息保存成功后,跳转到登录页面
else
render "new"
end
end
private
def user_params #用于过滤传入的参数
#password_confirmation是用来校对密码是否相同,同时为密码加密
params.require(:user).permit(:name,:password,:password_confirmation)
end
end
- 修改views的视图文件[2]
/! app/views/users/index.html.slim
h1
= link_to "注册", new_user_path
/! app/views/users/new.html.slim
h1 注册
- if @user.errors.any?
ul
- @user.errors.full_messages.each do |message|
li= message
= form_for @user, url: :users_create do |f|
p
= f.label "用户名:"
= f.text_field :name
p
= f.label "密码:"
= f.password_field :password
p
= f.label "确认密码:"
= f.password_field :password_confirmation
p
= f.button "提交"
|
= link_to "返回", user_index_path
- 修改路由文件(routes.rb)
#config/routes.rb
Rails.application.routes.draw do
get 'user/new'
get 'user/index'
- get 'user/create'
+ post 'user/create'
end
- 数据库迁移
rake db:migrate
- 启动服务
rails s
,让我来看看成果如何
样子挫一些,但功能还算实现了,这里提示全是中文的,是用到rails-i18n进行了本地化,可以参考Rails的本地化设置全过程
- 创建登录功能控制
rails g controller sessions new create
- 修改session_controller.rb
class SessionsController < ApplicationController
def new
@user = User.new
end
def create
user=User.find_by(name: user_params[:name]).try(:authenticate, user_params[:password])
if user
render plain: sprintf("欢迎,#{user.name}")
else
flash.now[:login_error]="无效的用户名或密码!"
render "new"
end
end
private
def user_params
params.require(:session).permit(:name, :password)
end
end
- 修改session的显示
/! app/views/applicants/new.html.erb
h1 登录
- if flash[:login_error]
p=flash[:login_error]
= form_for :session, url: :sessions_create do |f|
p
=f.label "用户名:"
=f.text_field :name
p
=f.label "密码:"
=f.password_field :password
p
=f.button "登录"
= ' '
= link_to "返回", user_index_path
/! app/views/users/index.html.slim
h1
= link_to "注册", new_user_path
|
= link_to "登录", session_new_path
- 修改路由
Rails.application.routes.draw do
get 'sessions/new'
- post 'sessions/create'
+ post 'sessions/create'
get 'user/new'
get 'user/index'
post 'user/create'
end
- 查检登录页面