Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using whodunnit to get User Instance

On my home page i display 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 the associated user but only the ID with whodunnit, but i would like to get a user instance to get a username. So insted of v.whodunnit i would like v.user.username.

I have been looking at a similar question but cant seem to figure out a way create the relation between a version and a 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 view

undefined method `user' for #<PaperTrail::Version:0x007fb24c08e868>
like image 929
Pierre Avatar asked Feb 18 '14 21:02

Pierre


2 Answers

An updated version of this for Rails 5.X

# config/initializers/paper_trail.rb
PaperTrail::Rails::Engine.eager_load!

module PaperTrail
  class Version < ::ActiveRecord::Base
    belongs_to :user, foreign_key: :whodunnit
  end
end
like image 78
Prothon Avatar answered Sep 19 '22 16:09

Prothon


There is an alternative way to do it:

class Version < PaperTrail::Version
    ...

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

If you need to add user model to the PaperTrail::Version class itself, then add a new initializer to your app:

config/initializers/papertrail_monkey_patch.rb

module PaperTrail
    class Version
        def user
            User.find(whodunnit) if whodunnit
        end
    end
end
like image 29
Maksim Gladkov Avatar answered Sep 16 '22 16:09

Maksim Gladkov