简体   繁体   English

Rails 数据库结果不一致

[英]Rails Inconsistent database results

I have a Rails application where there is a request to create elements on a table and another one, waiting, that reads if such element was created or not.我有一个 Rails 应用程序,其中有一个在表上创建元素的请求,另一个正在等待,该应用程序读取是否创建了此类元素。

Right now, I check the live Data and the waiting process never sees any new record for the table.现在,我检查实时数据,等待过程从未看到表的任何新记录。

Any ideas how to force a reconnection or anything that will update the model reference?任何想法如何强制重新连接或任何会更新模型参考的东西?

The basic idea:基本思路:

  • One user, through a POST, is creating a record (that i can see directly on the database).一个用户通过 POST 创建一条记录(我可以直接在数据库上看到)。
  • Another piece of code, that was running before the requests, is waiting for that record, but does not find it.在请求之前运行的另一段代码正在等待该记录,但没有找到它。

I'd appreciate any insights.我很感激任何见解。

The waiting request is probably using the ActiveRecord cache.等待请求可能正在使用 ActiveRecord 缓存。 Rails caches queries for the duration of a request, so if you run the exact same query multiple times in the same request, it will only hit the database the first time. Rails 在请求期间缓存查询,因此如果您在同一个请求中多次运行完全相同的查询,它只会在第一次访问数据库。

You can simulate this in the console:您可以在控制台中模拟:

Entity.cache { Entity.first; Entity.first }

In the logs, you'll see something like this (notice the second request says CACHE ):在日志中,您会看到类似这样的内容(注意第二个请求是CACHE ):

[2018-12-06T10:51:02.436 DEBUG (1476) #] Entity Load (4.9ms)  SELECT "entities".* FROM "entities" LIMIT 1
[2018-12-06T10:51:02.450 DEBUG (1476) #] CACHE (0.0ms)  SELECT "entities".* FROM "entities" LIMIT 1

To bypass the cache, you can use:要绕过缓存,您可以使用:

Entity.uncached { Entity.where(key: @key)&.last }

Using uncached will disable the cache inside the block, even if the enclosing scope is running inside a cached block.使用uncached将禁用块内的缓存,即使封闭范围在cached块内运行。

It seems that, for a running Rails application, if a running piece of code is looking for anything that has been updated by a new request, after the first began its execution, the updated data would not show, using active_record models.看起来,对于正在运行的 Rails 应用程序,如果正在运行的代码段正在寻找已被新请求更新的任何内容,在第一次开始执行后,更新的数据将不会显示,使用 active_record 模型。

The solution: Just run a raw query.解决方案:只需运行原始查询。

sql = "SELECT * FROM entities WHERE key = '"+key+"' ORDER BY ID DESC LIMIT 1;" records_array = ActiveRecord::Base.connection.execute(sql).values

I know it's a huge oversimplification and that there is probably an underlying problem, but it did solved it.我知道这是一个巨大的过度简化,并且可能存在潜在的问题,但它确实解决了它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM