MobileOverlord
MobileOverlord

Reputation: 4610

Get table name from ActiveRecord

I used ActiveRecord::Base.set_table_name to set my table name on a dynamically created ActiveRecord class. Now I need to know how to get that value later. The api docs don't mention anything on how to do this. Also, I can't derive the table name off the ActiveRecord class name because they are keyed differently than the table name.

Here is a better example of what I am doing

table_klass = Class.new(ActiveRecord::Base)
    ActiveRecord::Base.const_set(const_name,table_klass)
    app = @app
    table_klass.class_eval do
      after_save do
        @@channel.push self
      end
      set_table_name t.server_table
      establish_connection(
        :adapter  => "mysql2",
        :host     => app.db_host,
        :username => app.db_user,
        :password => app.db_pass,
        :database => app.db_name
      )
    end

In this case, if the const_name = Test and the database name is Database it should create a class of ActiveRecord::Base::DatabaseTest, which it does. But when I call table_name on it I get undefined local variable or method. Do I need to call table_name on the class?

Update: I got it working by calling instance.class.table_name

Upvotes: 30

Views: 28308

Answers (3)

Tim
Tim

Reputation: 1899

Late to the party.

I used the following rails code:

my_record = Record.id(0) # hypothetical code
table_name = my_record.class.table_name

Upvotes: 19

Suborx
Suborx

Reputation: 3669

class User < ActiveRecord::Base
end

User.table_name 
# 'users'

Upvotes: 12

Chowlett
Chowlett

Reputation: 46675

Have you tried table_name? Docs.

Upvotes: 52

Related Questions