How to change ActiveRecord's table name during runtime

喜你入骨 提交于 2021-02-07 05:51:53

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/5493846/how-to-change-activerecords-table-name-during-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!