Using whodunnit to get a user instance

On my homepage I show the latest updates using papertrail.

controller

@contributions = PaperTrail::Version.all.order("created_at DESC")

View

<% @contributions.each do |v| %>
    <h2><%= v.item.name %><small>by </small></h2>
    <% v.changeset.each do |data| %>
      <h4><%= data %></h4>
    <% end %>
    <%= v.whodunnit %>
<% end %>

Here I get a connected user, but only an identifier with whodunnit, but I would like to get a user instance to get the username . So insted v.whodunnit, I would like v.user.username.

I looked at a similar question , but didn't seem to find a way to create a connection between the version and the user.

User model

class User < ActiveRecord::Base
  has_many :versions, :foreign_key => 'whodunnit', :class_name => "PaperTrail::Version"
end

Version model

class Version < PaperTrail::Version
  belongs_to :user, :foreign_key => 'whodunnit'
end

EDIT

I get this when I have <% = v.user%> in the view

undefined method `user' for #<PaperTrail::Version:0x007fb24c08e868>
+4
source share
3

:

class Version < PaperTrail::Version
    ...

    def user
         User.find(whodunnit) if whodunnit
    end  
end

PaperTrail::Version, :

//papertrail_monkey_patch.rb

module PaperTrail
    class Version
        def user
            User.find(whodunnit) if whodunnit
        end
    end
end
+3

//paper_trail.rb

    # paper trail config ...
    # ...

    module PaperTrail
      class Version < ::ActiveRecord::Base
        belongs_to :user, foreign_key: :whodunnit
      end
    end
0

Updated version of this for Rails 5.X

PaperTrail::Rails::Engine.eager_load!

module PaperTrail
  class Version < ::ActiveRecord::Base
    belongs_to :user, foreign_key: :whodunnit
  end
end
0
source

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


All Articles