Rails update_attribute

╄→гoц情女王★ 提交于 2019-12-06 03:27:47

问题


Ive got the following problem. I have a model called user which has a column named activated. Im trying to update that value whith the method activated?, but it gives me the error: Validation failed: Password can't be blank, Password is too short (minimum is 6 characters) Which doesnt make sense to me, because im not touching the password field! I just want to update the activated column. Im putting here the code I think its relevant, but if you think you need more just ask :) Thank you very much in advance!

Model:

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

email_regex = /\A[\w+\-.]+@[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

Controller from which the method activated? is called

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

回答1:


Two things, first the ruby convention is to use predicate methods to return true or false only and not to do anything more like update a record. That is not causing your problem but is a deviation from what other programmers would expect. Secondly, instead of calling update_attributes try just calling:

update_attribute(:activated, true)

This should skip the rest of the callbacks for the record



来源:https://stackoverflow.com/questions/9879883/rails-update-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!