问题
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