Mongoid,在mongoid-history gem中设置自定义访问器字段

时间:2015-08-01 06:36:14

标签: ruby-on-rails ruby mongoid

我将mongoid-history gem添加到我的项目中。

根据指南in github,当我向跟踪器添加Userstamp时,会创建created_by字段,其中包含名为creator的访问者。

他们写过我可以通过gem config重命名它。

如何重命名此字段?

1 个答案:

答案 0 :(得分:1)

根据文档,Userstamp是另一个名为mongoid_userstamp的gem。该文档提供了示例代码,用于通过配置文件或每个模型内部配置名称:

配置/ mongoid_userstamp.rb:

# Default config (optional unless you want to customize the values)
Mongoid::Userstamp.config do |c|
  c.user_reader = :current_user
  c.created_name = :created_by
  c.updated_name = :updated_by
end

应用程序/模型/ your_model.rb

# Example model class
class Product
  include Mongoid::Document
  include Mongoid::Userstamp

  # optional class-level config override
  # mongoid_userstamp user_model: 'MyUser',
  #                   created_name: :creator,
  #                   updated_name: :updater,
end

# Example user class
class MyUser
  include Mongoid::Document
  include Mongoid::Userstamp::User

  # optional class-level config override
  # mongoid_userstamp_user reader: :current_my_user
end

在Mongoid History中,您可以在HistoryTracker类中包含配置,例如:

# app/models/history_tracker.rb
class HistoryTracker
  include Mongoid::History::Tracker
  include Mongoid::Userstamp
  # optional class-level config override
  mongoid_userstamp created_name: :updater,
                    updated_name: :another_updater,
end