无法从控制器重新加载 ActiveRecord 关联 [英] Can't reload ActiveRecord association from controller
问题描述
为此花了一个工作日.
我有
class Box
has_many :users, :through => :subscriptions
end
我也有自定义的 insert_new_users
和 associate_with(new_users)
方法,它们使用多个 INSERT 来快速完成工作.无论如何,他们工作得很好.我在associate_with"方法的末尾也有这一行:
I also have custom insert_new_users
and associate_with(new_users)
methods which use multiple INSERT to do their job quickly. Anyway, they work fine. I also have this line at the end of "associate_with" method:
def associate_with
# mysql INSERT here
self.users(true) # Should force reload
end
它在测试环境(控制器和模型测试)中运行时按预期工作,如果我删除强制重新加载的 true
参数,它会按预期失败.如果我 update_attributes
模型,它也可以在开发中从 script/console
工作.但是当我尝试从控制器update_attributes
时在开发或生产中失败.它只是不重新加载关联,我可以在日志中看到它,其中显示此查询的缓存(0.0 毫秒)".
It works as expected when running in test environment (both controller and model tests) and it fails as expected if I remove the true
argument, which forces the reload. It also works from script/console
in development if I update_attributes
the model. But fails in development or production when I'm trying to update_attributes
from controller. It simply does not reload associations and I can see it in logs, where it says "CACHE (0.0ms)" for this query.
奇怪的事情 - 它以前工作过,但由于某些原因我无法确定它停止工作的那一刻.我希望也许有人知道这怎么可能.
The weird thing - it worked before and I can't identify the moment it stopped working due to some reasons. I was hoping maybe someone knows how is this possible.
推荐答案
您正在看到 ActiveRecord SQL 查询缓存的效果.
You're seeing the effects of the ActiveRecord SQL query cache.
或者在对 uncached
self.class.uncached do
# ...
end
这将阻止 ActiveRecord 缓存块内任何查询的结果.如果你在很多地方都有代码,这可能很烦人.
This will stop ActiveRecord from caching the results of any queries inside the block. If you have code in many places, this may be annoying.
您还可以在完成插入后通过调用 connection.clear_query_cache
来清除缓存.
You can also clear the cache after you are done with your inserts by calling connection.clear_query_cache
.
这篇关于无法从控制器重新加载 ActiveRecord 关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!