2015-11-03 16 views
0

我有我的User類中定義這個方法:爲什麼我的`User`類定義的方法不斷返回未定義的方法?

def two_way_exists_with?(user1, user2) 
    return true if number_of_memberships(user1, user2) == 2 
    end 

當我試圖從我的控制檯稱它爲我不斷收到undefined method錯誤。

[3] pry(main)> two_way_exists?(u1, u2) 
NoMethodError: undefined method `two_way_exists?' for main:Object 
from (pry):3:in `__pry__' 
[4] pry(main)> u1.two_way_exists?(u1, u2) 
NoMethodError: undefined method `two_way_exists?' for #<User:0x007fe9e7eda228> 
from /[email protected]/gems/activemodel-4.1.12/lib/active_model/attribute_methods.rb:435:in `method_missing' 
[5] pry(main)> User.two_way_exists?(u1, u2) 
NoMethodError: undefined method `two_way_exists?' for #<Class:0x007fe9eaabf0a0> 
from /[email protected]/gems/activerecord-4.1.12/lib/active_record/dynamic_matchers.rb:26:in `method_missing' 

如何調用此方法?

+0

您定義了一個名爲'two_way_exists_with?'的方法,並嘗試調用一個名爲'two_way_exists?'的方法。注意名字中缺少'_with'。 –

+0

zomg ....感謝您的提示。那麼稱呼它的正確方法是什麼?在'u1'對象上,'User'類還是兩者都不? – marcamillion

+0

沒有看到你確切地定義了方法的地方,你可能已經定義了一個實例方法。這些都可以在你的課堂上使用,例如可能在'u1'上。一般來說,你應該得到一本Ruby的入門書,並學習一些關於方法範圍的知識。這是您一直需要的超級基本功能! –

回答

2

如果你已經在你的User類中定義了它,就像你說明的那樣,那麼它是一個實例方法,並且你將用戶作爲接收者來運行它。

例如

u1.two_way_exists_with?(u1, u2) 

然而,因爲它是一個實例方法,你已經提供給您的用戶對象之一爲self所以你只需要在其他用戶傳遞。

def two_way_exists_with?(other_user) 
    return true if number_of_memberships(self, other_user) == 2 
end 

u1.two_way_exists_with?(u2) 

由於number_of_memberships大概也是一個實例方法,有很好的機會,你不需要兩個用戶進入該方法無論是。

相關問題