2012-03-26 73 views
5

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

型号:

attr_accessor :password 
attr_accessible :name, :email, :password, :password_confirmation, :activated 
has_many :sucu_votes 

email_regex = /\A[\w+\-.][email protected][a-z\d\-.]+\.[a-z]+\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 

回答

12

两件事情,第一红宝石约定是使用谓词方法返回true或false,而不是做任何事情更像更新记录。这不会导致你的问题,但是与其他程序员所期望的不同。其次,而不是调用尝试的update_attributes只是打电话:

update_attribute(:activated, true)

这应该跳过回调其余备案

+0

非常感谢您!我之前确实有这样的感觉,但是由于另一个原因,它并没有工作。但它的一切都好了:) – gumlym 2012-03-27 09:55:13

相关问题