0

I need to create ActiveRecord class dynamically because i don't know the table name in advance. So i have a function to create class

def create_session_class(table_name) 
    session = Class.new(Session) do
      self.table_name = table_name
    end
end

The below count result is ok

session = create_session_class('test1_sessions')
session.where(status: 10).count   #could got correct result.

But i found when i try to query record from the class. it will use table name(sessions) to find not table name(test1_sessions). For example.

session = create_session_class('test1_sessions')
session.where(status: 10).each do |se|
 puts se.name
end

Above code will throw error

ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  relation "sessions" does not exist
LINE 5:                WHERE a.attrelid = '"sessions"'::regclass
                                      ^
:               SELECT a.attname, format_type(a.atttypid, a.atttypmod),
                  pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid,
a.atttypmod
            FROM pg_attribute a LEFT JOIN pg_attrdef d
              ON a.attrelid = d.adrelid AND a.attnum = d.adnum
           WHERE a.attrelid = '"sessions"'::regclass
             AND a.attnum > 0 AND NOT a.attisdropped
           ORDER BY a.attnum

I try to use load but doesn't work too.

session = create_session_class('test1_sessions')
session.where(status: 10).load.each do |se|
 puts se.name
end
Hung Weichien
  • 223
  • 2
  • 7

1 Answers1

-1

Why do you trying to create new class based on Session, instead of ActiveRecord::Base?

Anyway, it looks like a full duplicate for this question: Dynamically create a class inherited from ActiveRecord?

Community
  • 1
  • 1
BitOfUniverse
  • 5,903
  • 1
  • 34
  • 38