Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change ActiveRecord's table name during runtime

I am changing the table_name_prefix during running of a rails application (might sound weird, but really that's what I want). When the table_name_prefix changes for the ActiveRecord I reset the table names (table_name and quoted_table_name) by calling reset_table_name, and they change.. however I have another issue.

If the table name changes, after calling such a thing like count or a find the ActiveRecord object still operates with the table, which was used before.

How can reach to reset an ActiveRecord descendant, so that when the prefix, suffix, table_name changes it works with the new settings?

Thanks for your help!

like image 691
fifigyuri Avatar asked Mar 30 '11 23:03

fifigyuri


1 Answers

I found the explanation for the described behavior. Although reset_table_name resets the table name computed from the prefix, suffix (and maybe other things too), the table is initialized when a model is used and a query is generated. ActiveRecord works "on the top of" Arel, a relational algebra gem. When an ActiveRecord model is used a table is created and filled @arel_table instance variable. This caching is for performance purposes. If one wants to recreate the arel table, it can be reset by calling reset_column_information. I needed to have both reset_table_name and reset_column_information in order to get a new table for the new table name. Probably I will have to worry about the performance, if I reset the table often.

like image 76
fifigyuri Avatar answered Oct 12 '22 01:10

fifigyuri