Search code examples
sqlrubyinheritanceparent-childsuper

How to get Child class in inherited parent method in Ruby?


I am writing classes for a SQL Database in Ruby, a few of the query methods are common throughout all my classes so I want to move these methods into a parent class. I can't figure out how to get the original class call to show up in the parent class. Since my classes are the names of my tables, I need them to have access to them in my parent method. I've tried using self.class but that just returns Class, not the actual class I'm using the method on.

Here is the code I want to move into the parent class:

require_relative 'questions_databse.rb'

class User
  attr_accessor :id, :fname, :lname

  def self.find_by_id(id)
    user = QuestionDatabase.instance.execute(<<-SQL, id)
     SELECT
       *
     FROM
       users
     WHERE
       users.id = ?
    SQL
    user.map { |user| User.new(user) }.first
end

Now what I need to do is something like this:

require_relative 'questions_databse.rb'
require_relative 'modelbase.rb'

class User < ModelBase
  attr_accessor :id, :fname, :lname

  # no self.find_by_id(id)

Then I want the parent class to do something like this:

require 'active_support/inflector'

class ModelBase  
  def self.find_by_id(id)
    object = QuestionDatabase.instance.execute(<<-SQL, id)
      SELECT
        *
      FROM
        #{self.chid_class.name.tableize}
      WHERE
        #{self.chid_class.name.tableize}.id = ?
    SQL
    object.map { |object| self.child_class.new(object) }.first
  end
end

I have 4 other table classes that I use this method on, so I need to be able to have the code tell exactly what class called it so that the SQL query will run properly.

require 'active_support/inflector'

class ModelBase  
  def self.find_by_id(id)
    p self.class.name
  end
end

User.find_by_id(1) #=> "Class"

That is result when I use the self.class.name

I am learning how to code right now and this is the problem that the lesson is giving me. I know there may be easier ways to do this, but I probably haven't learned those yet.


Solution

  • In a class method like your find_by_id:

    class ModelBase  
      def self.find_by_id(id)
        p self.class.name
      end
    end
    

    self is the class itself (so self.class is Class) so you want to look at self.name:

    class ModelBase  
      def self.find_by_id(id)
        p name
      end
    end