Ricardo Jacas
Ricardo Jacas

Reputation: 156

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.

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:

I'd appreciate any insights.

Upvotes: 1

Views: 345

Answers (2)

Ricardo Jacas
Ricardo Jacas

Reputation: 156

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.

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.

Upvotes: 0

Kelvin
Kelvin

Reputation: 20932

The waiting request is probably using the ActiveRecord cache. 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.

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):

[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.

Upvotes: 1

Related Questions