1. 修改默认的首页
删除public下的index.html
在config/routes.rb中添加
map.connect '', :controller=>'home', :action=>'index'
此时可以使首页的指向controller home 下的 index 方法
那么我们需要首先建立home这个控制器
ruby script/generate controller home
在app/controllers/home_controller.rb中添加
def index
@me = User.new
end
再views下建立建立index.html.erb文件,内容是
<h1>Welcome <%= session[:me].name %></h1>
<div>
<ul>
<li><%= link_to 'Create task', new_task_path %></li>
<li><a href="/tasks/find">Find task</a></li>
<% if session[:me].is_admin %>
<li><%= link_to 'Create project', new_project_path %></li>
<% end %>
<li><a href="/users/view/<%= @me.id %>">About me</a></li>
</ul>
</div>
<div>
Add project status here.
</div>
2. 登陆过滤
为了迫使用户先登陆才能访问到首页,需要在home中建立过滤器
class HomeController < ApplicationController
before_filter :check_login
def index
@me = User.new
end
end
此时用户需先经过check_login
在home_controller.rb在最后添加方法
private
def check_login
unless session[:me]
flash[:notice] = 'please login'
redirect_to(:controller=>'users', :action=>'try_to_login')
end
end
3. 登陆处理
此时,如果用户的session中没有me这个值就会被重定向到users.try_to_login
编写users_controller.rb中的try_to_login方法
def try_to_login
@me = User.new
end
方法执行完之后会返回对于的页面try_to_login.html.erb
所以需要编写该文件,在views/users下建立该文件,内容
<% form_for(@me, :url=>{:action=>'login'}) do |u| %>
<table>
<tr>
<td>Username:</td>
<td><%= u.text_field :username %></td>
</tr>
<tr>
<td>Password:</td>
<td><%= u.password_field :password %></td>
</tr>
<tr>
<td colspan="2" align="center"><%= u.submit 'Submit' %></td>
</tr>
</table>
<% end %>
在该页面,用户填入用户名和密码,会提交到usrs.login方法
编写users_controller.rb中的login方法
def login
@me = User.new(params[:user])
if params[:user][:username].to_s.empty?
redirect_to(:controller=>'users', :action=>'try_to_login')
else
user = @me.try_to_login
unless user.to_s.empty?
session[:me] = user
end
redirect_to(:controller=>'home', :action=>'index')
end
end
接受请求之后先用提交的参数初始化User对象,验证用户名非空之后会交给user模型的try_to_login方法处理,否则会重定向回登陆页面,编写user.rb中的try_to_login方法
def try_to_login
transaction do
User.find(:first, :conditions=>["username=? and password=?", username, password])
end
end
try_to_login返回user模型的实例,再进行非空验证,通过则将用户实例写入session,再跳入首页
此时首页将回被渲染,但还会有问题,等下再说
为了让登陆地址显得好看一点,在routers.rb中加入一行配置
map.connect '/login.html', :controller=>'users', :action=>'try_to_login'
就是把首页的地址设置为了/login.html
4. 添加管理员帐户
上面说首页还会有问题,是因为我们的数据库中还没有一条用户数据,所以登陆是不可能成功的,那么我们就在数据库中添加一条管理员数据。
进入rails的控制台
$ ruby script/console $ admin = User.new $ admin.username = ‘admin’ $ admin.password = ‘admin’ $ admin.is_admin = true $ admin.email = ‘admin@localhost’ $ admin.name = ‘Mark Xu’ $ admin.save $ admin.id
可以看到最后一行命令回打印出来这条数据的id,如果是第一条那么应该会是1
好了,到此我今天的开发就算完毕了
浏览器进入http://localhost:3000
跳入登陆页面
输入用户名: admin,密码:admin,回车,进入首页
the End!
本人新博客:tuoxie.me