如何在运行时更改 ActiveRecord 的表名称
我在运行 Rails 应用程序期间更改 table_name_prefix
(可能听起来很奇怪,但这确实是我想要的)。当 ActiveRecord
的 table_name_prefix
更改时,我通过调用 重置表名称(
,并且它们发生了变化..但是我还有另一个问题。table_name
和 quoted_table_name
) reset_table_name
如果表名发生变化,在调用诸如 count 或 find 之类的东西后,ActiveRecord 对象仍然对之前使用过的表进行操作。
如何才能重置 ActiveRecord
后代,以便当前缀、后缀、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.
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我找到了所描述行为的解释。尽管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 anActiveRecord
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 callingreset_column_information
. I needed to have bothreset_table_name
andreset_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.