10

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!

fifigyuri
  • 5,771
  • 8
  • 30
  • 50
  • 2
    Good god, why would you ever do this? – Don Roby Mar 31 '11 at 00:17
  • i don't know how you could do that, but that's some question ! – Spyros Mar 31 '11 at 00:36
  • @DonRoby suppose that you want to switch between datasets, which are distinguished based on table_name_prefix. It is like db sharding, but I do not want to have new database, I can use only one db with multiple datasets. – fifigyuri Mar 31 '11 at 15:54
  • In case someone needs to play with something similar in the future, see this Q&A: https://stackoverflow.com/questions/52537951/changing-table-name-at-query-run-time-in-a-rails-application/52539763#52539763 – Nick M Sep 27 '18 at 15:43

1 Answers1

10

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.

fifigyuri
  • 5,771
  • 8
  • 30
  • 50
  • Can you put an example on it? I want to do this for a bunch of models at the same time. – Rhuan Jan 21 '21 at 11:24