Rails 4 x paper_trail:跟踪更新了哪些属性并显示它们的新值

Rails 4 x paper_trail: track which attributes are updated and display their new value

在我的 Rails 4 应用程序中,我使用 paper_trail 来跟踪用户对 Post 模型的记录所做的更改:

# post.rb
has_paper_trail :on => [:update, :destroy]

一个postbelong_to一个calendar和一个calendarhas_manypost,所以我显示对[=82所做的更改=]s 在位于 calendar index 视图的仪表板中:

<div id="my_changes">

  <% if @versions.any? %>

      <% @versions.each do |version| %>

      <% version.reify ? post = version.reify : post = Post.find_by_id(version.item_id) %>

      <p>
        <strong>
        <% if version.whodunnit.to_i === current_user.id %>
          You
        <% else %>
          <%= User.find_by_id(version.whodunnit).first_name %>
          <% end %>
        </strong> <%= conjugate(version.event) %> the post "<%= post.subject %>" in the <em><%= link_to Calendar.find_by_id(post.calendar_id).name, calendar_path(id: post.calendar_id) %></em> calendar <span id="update_time_ago">— <%= time_ago_in_words(version.created_at) %> ago.</span></p>

      <% end %>

  <% else %>

    <p>
      <span class="glyphicon glyphicon-hand-up" aria-hidden="true"></span><br/>There is no change to your posts yet.<br/>
      As soon as you update your calendar, a history of your changes will appear here.          
    </p>

  <% end %>

</div>

这工作正常。

我现在想要实现的 - 我不知道如何实现 - 不仅要显示哪个 post 已更新,还要显示 post 的哪个属性已更新已更新及其价值。

例如,而不是:

User_1 updated the post "Test post" in the Test calendar — 3 days ago.

我想要这样的东西:

User_1 updated the date / time / subject / copy / of the post "Test post" to NEW_POST_ATTRIBUTE_VALUE in the Test calendar — 3 days ago.

——————

更新:我确实阅读了paper_trail的文档,特别是Choose attributes to monitor部分,但是这似乎确实解释了如何实现我想要实现的目标。

——————

更新 2:我知道我正在寻找的内容实际上可能在 Diffing versions 部分进行了解释文档。

所以,我想在我的 index.html.erb 观点中,我可以做类似的事情:

post.versions.last.changeset

但是,我如何从那里提取我感兴趣的信息,例如:仅更新的属性及其新值,而不是 updated_at 属性,我无法 ignorepaper_trail 因为我还想知道 post 什么时候更新?

——————

更新 3:在 this Stack Overflow thread 中,@Maysam 建议:

With this behavior enabled, it is reasonably simple to get object.versions.map{|v| [v.created_at, v.changeset]} and then iterate over that structure to render your change log.

我不确定我是否理解在我的案例中如何实际迭代该结构:有什么建议吗?

——————

我真的可以用 paper_trail 实现吗?

.. I would like to .. display .. which attribute of the post has been updated and its value.

根据 Diffing Versions 上的文档:

.. to diff adjacent versions .. add an object_changes text column to your versions table .. PaperTrail will store the changes diff .. in each update version. You can use the version.changeset method to retrieve it.

所以,完成后,尝试添加

= debug post.versions.last.changeset

以您的观点。在那之后,if you know how to work with hashes 在 ruby,你应该可以开始了。