Development Environment
RUBY: ruby1.9.1
Rails: rails2.3.5
MySQL: mysql5.0.9
Driver: mysql-2.8.1-x86-mingw32.gem
IDE: rubymine2.0.1
1. Create view/login
Create login.html.erb;index.html.erb;loginfail.html. ERB under view/login.
The login.html. ERB code is as follows:
<H1> welcome to login! </H1> <br/> <% form_tag do %> <br/> <Table> <br/> <tr> <br/> <TD> User Name: </TD> <br/> <TD> <% = text_field ("user", "username ") %> </TD> <br/> </tr> <br/> <TD> password: </TD> <br/> <TD> <% = password_field ("user", "hashed_password ") %> </TD> <br/> </tr> <br/> <TD> </TD> <br/> <TD> <input type = "Submit" value = "login"/> <input type = "reset" value = "reset"/> </TD> <br/> </tr> <br/> </table> <br/> <% end %> </P> <p>
The Code index.html. ERB is as follows:
<H1> choose a page to look! </H1> <br/> <p> <% = link_to 'users',: controller => "users ",: action => "Index" %> </P> <br/> <p> <% = link_to 'products',: controller => "Products ",: action => "Index" %> </P> <br/> <p> <% = link_to 'logout',: Action => "login" %> </P>
Loginfail.html. ERB
<H1> invalid user/password combination </p> <br/> <% form_tag do %> <br/> <% = link_to 'back ',: action => "login" %> <br/> <% end %>
2. Create login_contoller.rb
The Code is as follows:
Class logincontroller <applicationcontroller <br/> def login <br/> If request. Get? <Br/> session [: user_id] = nil <br/> @ user = user. new <br/> else <br/> @ user = user. new (Params [: User]) <br/> logged_in_user = @ user. try_to_login </P> <p> If logged_in_user <br/> session [: user_id] = logged_in_user.id <br/> redirect_to (: Action => "Index ") <br/> else <br/> # Flash [: Notice] = "invalid user/password combination" <br/> redirect_to (: Action => "loginfail ") <br/> end </P> <p> def loginfail </P> <p> end <br/> # Clear logon information <br/> def reset <br/> Params [: user] ["username"] = NULL <br/> Params [: User] ["hashed_password"] = NULL <br/> end <br/>
3. Modify user. Rb
Add login information verification content
Def self. login (username, hashed_password) <br/> Password = hash_password (hashed_password | "") <br/> Find (: first, <br/>: conditions => ["username =? And Password =? ", Username, password]) <br/> end </P> <p> def try_to_login <br/> User. login (self. username, self. hashed_password) <br/> end
4. Modify routes. Rb
Add a login ing rule
Map. Connect '/login/login',: controller => "login",: Action => "login"
5. Modify view/user/index.html. ERB and view/product/index.html. ERB.
Add the following link
<% = Link_to 'logout',: controller => "login",: Action => "login" %>
<% = Link_to 'back to list',: controller => "login",: Action => "Index" %>
Demo effect: