ImranNaqvi ImranNaqvi - 2 months ago 11
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


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?

Answer

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.

Comments