Search code examples
ruby-on-railspaper-trail-gem

How to migrate paper_trail's whodunnit column from string to integer?


In a legacy Rails app using paper_trail, the whodunnit column is set to string and instead of the default current_user.id, this column holds the user's email. This is achieved by overriding user_for_paper_trail in ApplicationController:

def user_for_paper_trail
  current_user.email
end

Now I want to migrate to the default behavior of storing the id of the current user instead of the email.

So the approach I was thinking to take was something like this:

  • add a new integer column to the versions table, maybe named whodunnit_new;
  • remove user_for_paper_trail method in application controller and tell the models to write whodunnit info in whodunnit_new instead of whodunnit. This means, that for new versions, paper_trail is saving id in whodunnit_new and is not saving email in whodunnit;
  • backfill whodunnit_new for old records by finding the user by email and saving thier id in the new column;
  • drop the whodunnit column;
  • rename whodunnit_new to whodunnit and remove the setting in the models for using whodunnit_new.

The problem is - I couldn't find a setting, which can set the name of the whodunnit column, it seems to me, that it is hard-coded. I saw that there is an alias for the whodunnit method (called version_author).

I'm using Papertrail 10 and Rails 5.2.

So my question - what should be the proper way of doing the described migration.


Solution

  • .. I couldn't find a setting, which can set the name of the whodunnit column, it seems to me, that it is hard-coded.

    Correct, the column must be named whodunnit. It is not configurable.

    Otherwise your migration sounds good. Use a transaction and you won't need to temporarily rename the column. (Unless you're using MySQL, which has "weak" transactions, ie. not protected against DDL)