marcamillion
marcamillion

Reputation: 33785

Why does a method defined on my `User` class keep returning undefined method?

I have this method defined in my User class:

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

When I try to call it from my console I keep getting an undefined method error.

[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 /ruby-2.1.6@global/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 /ruby-2.1.6@global/gems/activerecord-4.1.12/lib/active_record/dynamic_matchers.rb:26:in `method_missing'

How do I invoke this method?

Upvotes: 0

Views: 79

Answers (1)

SteveTurczyn
SteveTurczyn

Reputation: 36880

if you've defined it in your User class as you illustrate, then it's an instance method and you'd run it with a user as the receiver.

e.g.

u1.two_way_exists_with?(u1, u2)

However since it is an instance method, you already have one of the user objects available to you as self so you would just need to pass in the other user.

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

u1.two_way_exists_with?(u2)

As number_of_memberships is probably also an instance method, chances are good that you don't need to pass two users into that method either.

Upvotes: 2

Related Questions