Rails update_attributes 方法更新部分属性问题

crazyjin · 2013年04月22日 · 最后由 crazyjin 回复于 2013年04月24日 · 4573 次阅读

我的表单是自己用 html 写的,没有 password 和 password_confirmation 字段 upate_attributes(params[:user]) 依然要验证 password 和 password_confirmation。 Rails 3.2.11

参考:http://ruby-china.org/topics/6719

#encoding: utf-8
class User < ActiveRecord::Base
  attr_accessible :birthday, :homeplace, :name,  :saysth, :secEmail, :sex, :password, :password_confirmation

  has_secure_password

  validates_presence_of :name, :message => "用户名不能为空!"
  validates_presence_of :secEmail, :message => "登录邮箱不能为空!"
  validates_presence_of :password, :message => "密码不能为空!"
  validates_presence_of :password_confirmation, :message => "密码验证不能为空!"
  validates_uniqueness_of :secEmail, :case_sensitive => false, :message => "该邮箱已经注册!"
  validates :secEmail, :format => {:with => /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, :message => "登录邮箱格式不正确!"}
  validates :name, :length => {:maximum => 16, :too_long => "昵称太长!"}
  validates :password, :length => {:minimum => 6,:maximum => 16, :too_short => "密码太短!",:too_long => "密码太长!"}

  before_save {|user| user.secEmail = secEmail.downcase}

  has_many :travels
end```

贴 Model 代码,参考连接里面好多版本不知道是哪个。

#2 楼 @crazyjin 因为写了这两条规则

validates_presence_of :password, :message => "密码不能为空!"
validates_presence_of :password_confirmation, :message => "密码验证不能为空!"

所以任何时候 password 都不能为空,但这两个是虚拟属性平时没有值。

简便方法可以改成这样

validates_presence_of :password, :message => "密码不能为空!", :on => :create
validates_presence_of :password_confirmation, :message => "密码验证不能为空!", :on => :create

创建的时候才校验。

#3 楼 @Rei 用你的方法解决了困扰了我几个小时的问题,谢谢

性别是 gender…

#5 楼 @xinkiang 华生,你发现盲点了

#3 楼 @Rei 这样 create 的时候不是还得出问题吗? 看明白了

#7 楼 @ChanceDoor create 的时候肯定有密码

用 if 也可以

validates_presence_of :password, :message => "密码不能为空!", :if => :password
validates_presence_of :password_confirmation, :message => "密码验证不能为空!", :if => :password_confirmation
end

#5 楼 @xinkiang 查了词典也查了网络。两个词差不多。http://zhidao.baidu.com/question/68298839.html

需要 登录 后方可回复, 如果你还没有账号请 注册新账号