Jean-Baptiste Jean-Baptiste - 6 months ago 17
Ruby Question

Calling a method inside model

I am trying to trigger a method from inside the model where it is defined. But I am getting an "undefined method `completed_mission_names'" when I try to start my server. Can anybody help me find what I'm doing wrong ?

class MenteeProfile < ActiveRecord::Base

# Update trackable attributes with succeeded missions
MenteeProfile.completed_mission_names

protected

def last_completed_mission_action
end

def self.completed_mission_names
end
end

Answer

Simplified to the max, you are trying to do this:

class A
  A.foo
  def self.foo
    puts 'Calling foo!'
  end
end

This does not work because the method foo is not defined when you try to invoke it. You must define it first, then you can call it. Like so:

class B
  def self.foo
    puts 'Calling foo!'
  end
  B.foo
end

You could also call just foo instead of B.foo from within the class definition. You can add the protected keyword anywhere you like, it will not have any impact on class methods whatsoever.

Comments