Paper trail manual versioning isn't working as expected

最后都变了- 提交于 2019-12-24 03:09:15

问题


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.

来源:https://stackoverflow.com/questions/48599246/paper-trail-manual-versioning-isnt-working-as-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!