2008-03-27

如何在update一条记录的部分字段时跳过某些校验

关键字: update 部分字段 校验
我照Agile Web Development with Rails里第11章用户管理的做了,用了password这个虚拟字段。
user.rb中的部分代码:
validates_length_of :password, :in => 6..20

def password
  @password
end

def password=(pwd)
  @password = pwd
  returen if pwd.blank
  created_new_salt
  self.hashed_password = User.encrypted_password(self.password, self.salt)
end

然后,我需要update该用户记录部分字段的值,比如email,im等等,但不希望改变密码,我用的是下面的办法。
user_controller.rb中的部分代码:
def update
  @user = User.find(params[:id])
  if @user.update_attributes(:email => params[:user][:email], :im => params[:user][:im])
    flash[:notice] = '个人信息修改完成'
    redirect_to :action => 'index'
  else
    render :action => 'edit'
  end
end

因为这个password字段并没有存储在数据库中,因此它值为空,于是每次都会出现校验错误:Password is too short (minimum is 6 characters)。

我想问一下只update部分字段应该用什么办法比较好(别的字段需要保留原来的值,可以先取出来;但由于SHA1加密,passowrd不能由hashed_password取出)?
还有能否在某些地方跳过部分校验?我这里的password需要在create和update时都要校验,但我想有的时候修改部分信息的时候不要校验password?
评论
wiisola 2008-03-27
theone 写道
wiisola 写道
theone 写道
update_all ["password =?", password], ['id=?,1]



那如何更新多个字段呢?第1个参数传hash好象不行。。


这样写
update_all ["username = ?, password =?", username, password], ['id=?',1]


谢谢,不过我找到办法了
validates_length_of :password, :in => 6..20, :allow_nil => true

原来allow_nil是这么个意思阿,以前误解了...
theone 2008-03-27
wiisola 写道
theone 写道
update_all ["password =?", password], ['id=?,1]



那如何更新多个字段呢?第1个参数传hash好象不行。。


这样写
update_all ["username = ?, password =?", username, password], ['id=?',1]
wiisola 2008-03-27
不见得 写道
update_attribute(s)

我本来就是用的这个
@user.update_attributes(:email => params[:user][:email], :im => params[:user][:im])
但是修改的时候会校验password,是通不过的,我就是想问有什么办法
不见得 2008-03-27
update_attribute(s)
wiisola 2008-03-27
theone 写道
update_all ["password =?", password], ['id=?,1]



那如何更新多个字段呢?第1个参数传hash好象不行。。
theone 2008-03-27
update_all ["password =?", password], ['id=?,1]
发表评论

提醒: 该博客已发表在公共论坛,博客所有留言会成为论坛回贴,留言请注意遵守论坛发贴规则

您还没有登录,请登录后发表评论

wiisola
搜索本博客
最近加入圈子
存档
最新评论