PaperTrail: info_for_paper_trail out of controller context

I use paper_trail gem for versions of my models.

So far, my model depends on the info_for_paper_trail method in ApplicationController :

 class ApplicationController < ActionController::Base # Extra columns to store along with PaperTrail `versions` def info_for_paper_trail { revision_id: @revision.id, revision_source_id: @revision_source.id } end end 

This works fine in the context of the controller, but is there a way so that I can replicate such things outside the context of the controller (e.g. a deferred job)?

I tried creating a virtual attribute called revision and passing proc to has_paper_trail , but it will fail with the exception of method not found :

 # Attempt to solve this in the model class Resource < ActiveRecord::Base # Virtual attribute attr_accessor :revision # Attempt to use virtual attribute only if set from delayed job has_paper_trail meta: proc { |resource| resource.revision.present? ? { revision_id: resource.revision.id, revision_source_id: revision.revision_source.id } : {} } end # Gist of what I'm trying to do in the delayed job resource = Resource.new resource.revision = Revision.new(user: user, revision_source: revision_source) resource.save! 

I am assuming based on this result that meta cannot take proc , and plus I don't like how this solution smells anyway ...

+4
source share
2 answers

You need to set these values ​​in the code if you are working outside the controller:

 ::PaperTrail.controller_info = { revision_id: revision.id, revision_source_id: revision_source.id } ::PaperTrail.whodunnit = user.id 

Then the model will select additional values, as usual, from the controller.

I got this information by looking at the PaperTrail::Controller module. In particular, consider the set_paper_trail_controller_info and set_paper_trail_whodunnit methods that run as filters before starting work.

+4
source

I think you can just do:

 class Resource < ActiveRecord::Base # Virtual attribute attr_accessor :revision, :revision_source # Attempt to use virtual attribute only if set from delayed job has_paper_trail meta: { revision_id: :get_revision_id, revision_source_id: get_revision_source.id } def get_revision_id resource.revision.try(:id) end def get_revision_source_id resource.revision_source.try(:id) end end 
0
source

Source: https://habr.com/ru/post/1494491/


All Articles