开发环境
Ruby:Ruby1.9.1
Rails:Rails2.3.5
Mysql:Mysql5.0.9
Driver:mysql-2.8.1-x86-mingw32.gem
IDE:Rubymine2.0.1
一、创建View/login
在View/login下创建login.html.erb、index.html.erb、loginFail.html.erb
login.html.erb代码如下:
<h1>Welcome to login!</h1> <% form_tag do %> <table> <tr> <td>User name:</td> <td><%= text_field("user", "username") %></td> </tr> <tr> <td>Password:</td> <td><%= password_field("user", "hashed_password") %></td> </tr> <tr> <td></td> <td><input type="submit" value=" login " /> <input type="reset" value=" reset " /></td> </tr> </table> <% end %>
index.html.erb代码如下:
<h1>Choose a page to look!</h1> <p><%= link_to 'Users', :controller=>"users",:action=>"index" %></p> <p><%= link_to 'Products', :controller=>"products",:action=>"index"%></p> <p><%= link_to 'Logout', :action=>"login"%></p>
loginFail.html.erb
<h1>Invalid user/password combination</h1> <%form_tag do%> <%= link_to 'Back', :action=>"login" %> <%end%>
二、创建login_contoller.rb
代码如下:
class LoginController < ApplicationController def login if request.get? session[:user_id] = nil @user = User.new else @user = User.new(params[:user]) logged_in_user = @user.try_to_login if logged_in_user session[:user_id] = logged_in_user.id redirect_to(:action => "index") else # flash[:notice] = "Invalid user/password combination" redirect_to(:action => "loginFail") end end end def loginFail end #清空登录信息 def reset params[:user]["username"]=null params[:user]["hashed_password"]=null end end
三、修改user.rb
添加登录信息验证内容
def self.login(username, hashed_password) password = hash_password(hashed_password || "") find(:first, :conditions => ["username = ? and password = ?",username, password]) end def try_to_login User.login(self.username, self.hashed_password) end
四、修改routes.rb
添加login映射规则
map.connect '/login/login',:controller=>"login",:action=>"login"
五、修改view/user/index.html.erb及view/product/index.html.erb
添加如下链接
<%= link_to 'Logout', :controller=>"login",:action=>"login" %>
<%= link_to 'Back to List', :controller=>"login",:action=>"index" %>
演示效果: