简体   繁体   English

Ruby On Rails帮助Paper_trail gem

[英]Ruby On Rails help on Paper_trail gem

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. 对于我使用paper_trail gem的历史记录,我有一个过滤历史记录以显示给用户的问题,我将其配置为将current_user id跟踪到Whodunnit字段中。 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. 我的用户有role_id,它从Roles表中指定了角色。另外,我还有另一个表,其中包含具有id和user_id字段的某些项目。 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'. 现在我的问题是如何根据用户的角色从Versions表中获取特定的行,例如ex:如果用户角色为“ SomeRole”,则它仅返回由具有相同角色“ 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? 有没有简单的方法可以做到呢?还是我应该像逐个选择那样对其进行硬编码,而不是检查其角色的所有user_id等等? Hope you understood my messy way of explaining 希望你能理解我的解释方式

In similar situation I used this solution: 在类似情况下,我使用以下解决方案:

1) Added user_id field to versions 1)在版本中添加了user_id字段

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) (whodunnit是一个文本字段,我不想将其用作关联键)

2) Defined association in Version model: 2)在版本模型中定义的关联:

# /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) 3)在ApplicationController中(或您需要的地方)设置info_for_paper_trail

  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' })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM