开发环境
Ruby: Ruby1.9.1
Rails: Rails2.3.5
Mysql:Mysql5.0.9
Driver:mysql-2.8.1-x86-mingw32.gem
IDE:Rubymine2.0.1
一、创建数据表Users
利用RubyMine自带的Scaffold工具创建数据表Users,也可以手动创建
二、创建Controller和View
Ruby项目—>右键—>Create Model
完成后将自动生成相应的文件
三、修改Model user.rb
利用Digest/SHA1对密码进行加密,实现加密保存
修改后代码如下:
require "digest/sha1" class User < ActiveRecord::Base attr_accessor :hashed_password,:repassword attr_accessible :username, :hashed_password, :repassword validates_uniqueness_of :username validates_presence_of :username, :hashed_password def before_create self.password = User.hash_password(self.hashed_password) end def after_create @hashed_password = nil end def before_update self.password = User.hash_password(self.hashed_password) end def after_update @hashed_password = nil end private def self.hash_password(hashed_password) Digest::SHA1.hexdigest(hashed_password) end end
四、修改users_controller.rb
修改update方法,实现当进行edit操作时先判断password与 password_confirm是否一致,
如果一致,则进行update操作,否则提示用户password 与 password_confirm 输入不一致
修改后代码如下:
def update @user = User.find(params[:id]) respond_to do |format| print "user: #{params[:user]}" if params[:user]["hashed_password"] == params[:user]["repassword"] if @user.update_attributes(params[:user]) flash[:notice] = 'User was successfully updated.' format.html { redirect_to(@user) } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @user.errors, :status => :unprocessable_entity } end else flash[:notice] = 'Password and Password confirm are not the same' format.html { render :action => "edit" } format.xml { render :xml => @user.errors, :status => :unprocessable_entity } end end end
五、修改users/edit.html.erb及users/show.html.erb
对password字段的显示做修改
edit.html.erb修改后代码如下:
<%= f.label :username %>
<%= f.text_field :username %>
<%= f.label :password %>
<%= f.password_field :hashed_password %>
<%= f.label :password_confirm %>
<%= f.password_field :repassword %>
<%= f.submit 'Update' %>
<% end %> <%= link_to 'Show', @user %> | <%= link_to 'Back', users_path %>
show.html.erb修改后代码如下:
Username: <%=h @user.username %>
Password: <%=h @user.hashed_password %>
<%= link_to 'Edit', edit_user_path(@user) %> | <%= link_to 'Back', users_path %>
六、修改routes.rb
添下如下映射规则
map.connect '/users',:controller=>"user",:action=>"index"
演示效果:
Create User:
Update User: