Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 596
MobileOverlord Avatar asked Apr 26 '12 13:04

MobileOverlord


2 Answers

Have you tried table_name? Docs.

like image 168
Chowlett Avatar answered Oct 14 '22 21:10

Chowlett


Late to the party.

I used the following rails code:

my_record = Record.id(0) # hypothetical code table_name = my_record.class.table_name 
like image 29
Tim Avatar answered Oct 14 '22 23:10

Tim