I am trying to automatically set created_by in my models to currently authenticated user without explicitly passing down user as an argument. I am using devise for authentication and for setting user globally on each request I am using new rails api ActiveSupport::CurrentAttributes like so:
# app/models/current.rb
class Current < ActiveSupport::CurrentAttributes
attribute :user
end
# config/initializers/warden.rb
Warden::Manager.after_set_user { |user, auth, opts| Current.user = user }
Then I have Owned concern
# app/models/concerns/owned.rb
module Owned
extend ActiveSupport::Concern
included do
belongs_to(
:created_by,
class_name: "User",
foreign_key: "created_by_id",
default: -> { Current.user }
)
end
end
which is included in models in which I want to automatically set created_by.
It works but recently I got bug where created_by was assigned to wrong person and I am wondering if it could be caused by code I described above because its not thread safe. I am unable to reproduce the bug again and I don't know how to test for such potential race conditions. So my questions are: Is my usage of CurrentAttributes correct and my code in general? Is there a better way how to automatically set created_by?