我正在Railcasts上练习Rails,遇到了一些需要理解的内容。
我不明白authenticate方法中的"self"是什么意思。于是我删除了它,并测试了我的应用程序的登录功能,结果出现了错误:
error:
**NoMethodError in SessionsController#create
undefined method `authenticate' for #<Class:0x00000102cb9000**>
我希望有人能够解释一下 "Self" 到底是做什么的。我一直试图弄清楚到底发生了什么,但是却无法理解。
该方法在模型中定义,并在sessions_controller中调用.. 我一直在不断地删除我的应用程序并从头开始学习它,每次重新开始时,许多事情对我来说都很有意义,但是我被卡在了“self”上。
我只是那种喜欢了解为什么某些东西工作的人。
控制器:
def create
user = User.authenticate(params[:email], params[:password])
if user
session[:user_id] = user.id
redirect_to root_path, :notice => "Logged In"
else
flash.now.alert = "Invalid credentials"
render "new"
end
end
模型:
def self.authenticate(email, password)
user = find_by_email(email)
if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt)
user
else
nil
end
end
def object.my_foo_method
。在obj
上定义了my_foo_method
方法。在你的回答中,self
是Class
类的对象(即MyClass
类)。因此,它定义了该类的方法。 - Swanand@
符号吗,例如 @instance = ...? - Michael Durrant