Rails memoize the wrong value for current user

162 views Asked by At

I've been building a small web app and have been using Michael Hartl's guide for creating accounts / authorization.

Whilst testing the app amongst friends, a couple have gone on the website and found themselves to logged in as the wrong current user.

The app defines the current user like so

def current_user
  if session[:user_id]
    @current_user ||= User.find_by(id: session[:user_id])
  end
end

Since I have removed using memoize and query the db every time, the issue has resolved itself. Furthermore, this isn't the only instance i've had with wrong values being memoized in the app, but this is the most concerning as it concerns user accounts.

The other method that memoized wrong values looked like the following

def favourites
  @favourites ||= Competition.favourites.include?(self.id)
end

Would anyone be able to shed any light on why Rails might memoize the wrong value?

I wondered if it was thread related but I think this is a red herring. I am using only 1 thread on a puma server (config below). ENV['RAILS_MAX_THREADS'] and ENV['WEB_CONCURRENCY'] are both set to 1 in production.

workers Integer(ENV['WEB_CONCURRENCY'] || 2)
threads_count = Integer(ENV['RAILS_MAX_THREADS'] || 5)
threads threads_count, threads_count

preload_app!

rackup      DefaultRackup
port        ENV['PORT']     || 3000
environment ENV['RACK_ENV'] || 'development'

on_worker_boot do
  # Worker specific setup for Rails 4.1+
  # See: https://devcenter.heroku.com/articles/deploying-rails-applications-with-the-puma-web-server#on-worker-boot
  ActiveRecord::Base.establish_connection
end
0

There are 0 answers