How to add a method to the versions model of Paper_trail?

你。 提交于 2019-12-23 02:49:18

问题


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:


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


来源:https://stackoverflow.com/questions/20982804/how-to-add-a-method-to-the-versions-model-of-paper-trail

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!