How to set whodunnit for paper_trail when creating a new user?
Asked Answered
O

2

9

The paper_trail gem tracks versions, and does a good job. However, there is one edge case I've been noticing. For most objects, the application controller sets whodunnit if you are logged in, and then all objects that are created during that session have a version that records "whodunnit" according to who is logged in.

The interesting case is where nobody is logged in because a new user is signing up. The user is created with a "nil" whodunnit, which is wrong because actually the user was created by themselves.

Of course, whodunnit can't know the id of the user before the user record is saved. I know this.

However, this creates a conflict later, as various batch jobs also modify user records, and not being in a web session, also create versions with nil whodunnit records.

Now I can't tell who created the user - some batch import process, or the user.

I'm pondering various solutions, like perhaps rummaging around the Papertrail::Versions table for that object and fixing whodunnit, but that seems pretty unclean.

Any advice?

Oswald answered 28/1, 2016 at 21:31 Comment(0)
O
5

You can force whodunnit in the create action on your controller.

before_filter :only => [:create] do
  PaperTrail.request.whodunnit = "Public User"
end

If you insist on having the user id in the version table, you can do this:

ActiveRecord::Base.transaction do
  @user.save!
  @user.versions.last.update_attributes!(:whodunnit => @user.id)
end
Orwin answered 28/1, 2016 at 22:21 Comment(0)
O
2

For someone reading this in future, John-Naegle's answer

PaperTrail.whodunnit = "Public User"

Does not work anymore. Use

PaperTrail.request.whodunnit = "Public User"
Octarchy answered 17/10, 2022 at 16:17 Comment(1)
Yep, you are right.Oswald

© 2022 - 2024 — McMap. All rights reserved.