0

I'm trying to call an instance method (defined in model) from the instance variable in controller but could not get that work and server logs saying

undefined method `active_users' for #< Admin

controller

@admin = Admin.first
@admin.active_users

Admin Model

def self.active_users
  byebug
end

I know that we can call it through the class directly like Admin.active_users .

Why is it not accessible by instance of the class?

2 Answers 2

2

active_users method is defined for Admin object, not for its instances.

I do not know what you are trying to do, but message receiver matters.

To make @admin.active_users work, define a method an instance method:

def active_users
  byebug
end

The thing is, that active_users (both with and without self) are instance methods. It is just that objects for which these methods defined are different.

The method with self is a "class instance method", while the one without self is an "instance method", e.g. method accessible by instances of the class Admin.

Sign up to request clarification or add additional context in comments.

4 Comments

i simply want to call an instance method directly from instance variable . can you guide me to some cool way in rails
i checked that too . but did not worked . but i try it again
@ImranNaqvi: the problem is that active_users is a method on completely separate instance, Admin of type Class, not @admin of type Admin.
@SergioTulentsev no actually moving to class method worked . dont know why it didn't worked on first attempt . thanks
0

When you write def self.something_method, method will be available only for class, as in your example. If you want create method for object, you have to create method without self, like this: def something_method. For example:

class Admin
  def self.class_method
    p 'class method'
  end

  def something_method
    p 'method for object' 
  end
end

@admin = Admin.create(something_params)
 # You can also use 'Admin.new', but it will not save your admin in database, or 'Admin.first', like in your example.
@admin.something_method
#=> 'method for object'
@admin.class_method
#=> not working :( 

Admin.something_method
#=> not working :( 
Admin.class_method
#=> 'class method'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.