如何在运行时更改ActiveRecord的表名 [英] How to change ActiveRecord's table name during runtime
问题描述
我正在运行Rails应用程序时更改 table_name_prefix
(可能听起来很奇怪,但这确实是我想要的).当 table_name_prefix
更改为 ActiveRecord
时,我通过调用重置表名(
,并且它们会更改..但是我还有另一个问题. table_name
和 quoted_table_name
)reset_table_name
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.
如果表名更改,则在调用诸如count之类的事情或找到ActiveRecord对象之后,该表仍会与以前使用的表一起运行.
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.
如何才能重置 ActiveRecord
后代,以便在前缀,后缀,table_name更改时能与新设置一起使用?
How can reach to reset an ActiveRecord
descendant, so that when the prefix, suffix, table_name changes it works with the new settings?
感谢您的帮助!
推荐答案
我找到了所描述行为的解释.尽管 reset_table_name
会重置根据前缀,后缀(可能还有其他东西)计算出的表名,但是在使用模型并生成查询时会初始化表. ActiveRecord
在关系代数宝石 Arel
的顶部"工作.使用 ActiveRecord
模型时,将创建一个表并填充 @arel_table
实例变量.此缓存是出于性能目的.如果要重新创建arel表,可以通过调用 reset_column_information
将其重置.我需要同时具有 reset_table_name
和 reset_column_information
才能获得新表名称的新表.如果我经常重置表,也许我将不得不担心性能.
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.
这篇关于如何在运行时更改ActiveRecord的表名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!