Rails update_attribute

我有以下问题。 我有一个名为user的模型,它有一个名为activated的列。 我试图更新该方法激活方法?但它给我错误:validation失败:密码不能为空,密码太短(最少6个字符)这对我没有意义,因为我不接触密码字段! 我只想更新激活的列。 我把这些代码放在这里我认为它是相关的,但如果你认为你需要更多,请问:)非常感谢你提前!

模型:

attr_accessor :password attr_accessible :name, :email, :password, :password_confirmation, :activated has_many :sucu_votes email_regex = /\A[\w+\-.]+@[az\d\-.]+\.[az]+\z/i validates :name, :presence => true, :length => { :maximum => 50 } validates :email, :presence => true, :format => {:with => email_regex}, :uniqueness => { :case_sensitive => false } validates :password, :presence => true, :length => { :within => 6..15 }, :confirmation => true before_save :encrypt_password def activated? self.update_attributes!(:activated => true) return self.activated end 

控制器从哪个方法激活? 叫做

 def activate if request.get? user=User.find_by_id(params[:id]) if user.activated? flash[:notice]="Your account has been activated" #redirect_to :controller => 'sessions', :action => 'new' else flash[:error]="We couldnt activate the account" redirect_to :controller => 'sessions', :action => 'new' end end end 

两件事,首先是ruby约定是使用谓词方法仅返回true或false而不是更新更新记录。 这不会导致你的问题,但是偏离了其他程序员的期望。 其次,不要调用update_attributes而只是调用:

update_attribute(:activated, true)

这应该跳过记录的其余回调