ImranNaqvi ImranNaqvi - 25 days ago 7
Ruby Question

call instance method with class instance variable - ruby on rails

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


@admin = Admin.first

Admin Model

def self.active_users

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

Why is it not accessible by instance of the class?


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

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.