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 

物質偏好。