How to add a method to the versions model of Paper

2019-06-03 17:35发布

I want to create the following method for paper_trail versions:

def user
  User.find self.whodunnit.to_i
end

So that I can access a version's user naturally in my app as if it has a belongs_to relation.

Where should I put this function (folder and file name) in order to override / add it to paper_trail's version model?

1条回答
Luminary・发光体
2楼-- · 2019-06-03 18:02

You could put this in an initializer (e.g., config/initializers/paper_trail.rb) that opens the PaperTrail::Version class:

module PaperTrail
  class Version < ActiveRecord::Base
    def user
      User.find self.whodunnit.to_i
    end
  end
end

You'll want to confirm that your Version model is PaperTrail::Version; older versions of the gem use just Version. In that case, just remove the outer module statement.

You could also create a custom class inheriting from Version, and specify that in your has_paper_trail call. For example (from the README):

class PostVersion < PaperTrail::Version
  # custom behaviour, e.g:
  self.table_name = :post_versions
end

class Post < ActiveRecord::Base
  has_paper_trail :class_name => 'PostVersion'
end
查看更多
登录 后发表回答