无法从控制器重新加载 ActiveRecord 关联
为此花了一个工作日。
我还有
class Box
has_many :users, :through => :subscriptions
end
自定义 insert_new_users
和 associate_with(new_users)
方法,它们使用多个 INSERT 来快速完成工作。 不管怎样,他们工作得很好。 我在“associate_with”方法的末尾也有这一行:
def associate_with
# mysql INSERT here
self.users(true) # Should force reload
end
在测试环境(控制器和模型测试)中运行时它按预期工作,并且如果我删除 true
参数,它会按预期失败,这强制重新加载。 如果我update_attributes
模型,它也可以在开发中的script/console
中工作。 但当我尝试从控制器更新属性时,开发或生产失败。 它只是不会重新加载关联,我可以在日志中看到它,其中显示此查询的“CACHE (0.0ms)”。
奇怪的是 - 它以前有效,但由于某些原因我无法确定它停止工作的那一刻。 我希望也许有人知道这怎么可能。
Spent a working day on this.
I have
class Box
has_many :users, :through => :subscriptions
end
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
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您将看到 ActiveRecord SQL 查询缓存的效果。
要么将对
users
关联的预插入引用包装在对uncached
的调用中,这将阻止 ActiveRecord 缓存块内任何查询的结果。 如果您在很多地方都有代码,这可能会很烦人。
完成插入后,您还可以通过调用
connection.clear_query_cache
清除缓存。You're seeing the effects of the ActiveRecord SQL query cache.
Either wrap the pre-INSERT references to the
users
association in a call touncached
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.
You can also clear the cache after you are done with your inserts by calling
connection.clear_query_cache
.到目前为止,我已经能够通过以下方式欺骗 AR:
So far I've been able to trick AR with the following:
我能够完全清除缓存的唯一方法是调用
reload
。 例如,您可以调用用户重新加载
并且它应该强制清除缓存,包括任何关系或关联。
The only way I've been able to fully clear the cache is to call
reload
. For example, you could callUser.reload
and it should force a cache clear including of any relations or associations.