Ruby On Rails help on Paper_trail gem

421 views Asked by At

So I have a project with authentication of users, and history tracking of some models. For the history I use the paper_trail gem, I have a problem of filtering the history to show to the user, I have configured it to track the current_user id into the Whodunnit field. My user has role_id which specifies the role from the Roles table Also i have another table with some items that have id and user_id fields. And now my problem is how to take specific rows from Versions table according to the role of the user, like for ex: if user role is 'SomeRole' it has to return only those actions done by the users that have the same role 'SomeRole'. I know that i can take out all the actions by

@versions = PaperTrail::Version.order('created_at')

but have no idea on how to filter to select only those that are satisfying for my uses. Is there an easy way to do it or should i hardcode it like selecting one by one, than check all user_id of their roles and so on so forth? Hope you understood my messy way of explaining

1

There are 1 answers

0
lightalloy On BEST ANSWER

In similar situation I used this solution:

1) Added user_id field to versions

class AddUserIdToVersions < ActiveRecord::Migration
  def change
    add_column :versions, :user_id, :integer
    add_index :versions, :user_id
  end
end

(whodunnit is a text field and I didn't want to use it as association key)

2) Defined association in Version model:

# /app/models/version.rb

class Version < PaperTrail::Version
  belongs_to :user

  # ... some other custom methods
end

and in User model:

 has_many :versions

3) Set info_for_paper_trail in ApplicationController (or where you need it)

  def info_for_paper_trail
    { user_id: current_user.try(:id) } if user_signed_in?
  end

So I'm able to access versions like:

@user.versions

So in your case it would be:

Version.joins(:user).where(users: { role: 'SomeRole' })