Paper trail manual versioning isn't working as

2019-07-14 18:05发布

问题:

I'm using the paper_trail gem. My use case involves creating versions when I explicitly want to instead of on callbacks like on: [:update] or something.

I did so by adding on: [] in my my_model.rb and using paper_trail.touch_with_version on my model instance. The problem is whenever I do this the first time the version is saved with nil attributes. Weird enough, the next time call paper_trail.touch_with_version it saves it correctly with all attributes correctly initialised.

Sample logs from my rails console:

document = Document.first
 #<Document:0x0000123456
id: 1,
name: "Sample document">

document.paper_trail.touch_with_version

document.versions.last.reify.name
=> nil

document.paper_trail.touch_with_version

document.versions.last.reify.name
=> "Sample document"

What's really peculiar is that if I try doing document.paper_trail.touch_with_version followed by document.versions.last.reify.name I correctly get name of my document but if I exit console and repeat this process the first time the attributes of the object saved in that version is again nil.

I'm probably doing something obvious but didn't find anything on wiki that talks about this. Can someone explain to me where I'm messing up?

Update: I traced back the code in paper_trail library and found where the issue is. I found the anomaly in record_trail.rb:

# @api private
def attribute_in_previous_version(attr_name)
  if @in_after_callback && RAILS_GTE_5_1
    @record.attribute_before_last_save(attr_name.to_s)
  else
    @record.attribute_was(attr_name.to_s)
  end
end

So in console the @record.attribute_before_last_save(attr_name.to_s) is giving me nil but if I try @record.attribute_was('name') in my console it gives me the correct attribute(in this case name) of the record.