5

我在铁轨上只是练习一些铁轨,遇到了一些我正在尝试理解的东西。红宝石在轨道上做了什么?

我没有得到验证方法的“自我”。所以我删除它和测试我的应用程序的登录,看看它会显示一个错误,它没有:

error: 

**NoMethodError in SessionsController#create 
undefined method `authenticate' for #<Class:0x00000102cb9000**> 

我真的很感激,如果有人能解释什么是“自我”在做什么。我试图弄清楚到底发生了什么,但无法摆脱困境。

方法在模型中定义,并在会话控制器中调用.. 我一直在不断删除我的应用程序,并从头开始获取它的窍门,每次我重新开始时,许多事情对我来说都有意义,但我是卡在“自我”。

我只是喜欢理解为什么有效的人的类型。

控制器:

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 

回答

13

这是一个基本的ruby问题。在这种情况下,self用于定义类方法。

class MyClass 
     def instance_method 
     puts "instance method" 
     end 

     def self.class_method 
     puts "class method" 
     end 
    end 
使用了哪些这样的

instance = MyClass.new 
    instance.instance_method 

或者:

MyClass.class_method 

。希望清除的东西一点点。另请参考:http://railstips.org/blog/archives/2009/05/11/class-and-instance-methods-in-ruby/

+1

稍微扩展一下你的答案:'def object.my_foo_method'。在'obj'上定义'my_foo_method'。在你的回答的上下文中,'self'是类'Class'(即类MyClass')的对象。因此,它定义了该类的方法。 – Swanand

+0

不应该在实例中使用“@”符号,例如@instance = ...? –

+0

考虑到它的轨道,并可能会在视图中使用 –

2
class User 
    def self.xxx 
    end 
end 

是定义类方法而

class User  
    def xxx 
    end 
end 

将定义一个实例方法的一种方式。

如果你删除自我。从DEF,当你做

User.authenticate 

因为你试图调用一个类,而不是类的实例的方法,你会得到一个方法未找到错误。要使用实例方法,您需要一个类的实例。

4

self定义了而不是实例类的方法。因此,与def self.authenticate,你可以做到以下几点:

u = User.authenticate('[email protected]','[email protected]') 

而不是做的......

u = User.new 
u.authenticate('[email protected]','[email protected]') 

这样的话,你没有创建的用户实例验证之一。

+0

除了为了避免需要实例化类来使用方法,还有其他原因来定义类方法而不是实例方法吗? – LazerSharks

3

完成的缘故,并挫败未来的头痛,我想也指出,两者是等价的:

class User 
    def self.authenticate 
    end 
end 

class User 
    def User.authenticate 
    end 
end 

物质偏好。