Method: ActivemodelObjectInfo::TableDefinition#operation_columns

Defined in:
lib/activemodel_object_info/table_definition.rb

#operation_columns(*fields, **options) ⇒ Object

生成操作相关的字段。包含操作人、操作时间等信息。

Examples:

operation_columns(:create, with_operator: true, operator_prefix: 'my_', operator_suffix: '_user')
# => 会生成名为 'my_create_user' 的字段用来记录创建人信息。

Parameters:

  • fields (Symbol, String)

    要生成的操作字段的名称。可以是字符串也可以是符号格式。相当于实际的前缀,会根据后续设置选项决定生成的字段内容。

  • options (Hash)

    具体的设置选项,详见选项介绍。

Options Hash (**options):

  • :operator_prefix (String)

    操作人字段前缀,默认为 nil

  • :operator_suffix (String)

    操作人字段后缀,默认为 ‘_by’

  • :with_operator (Boolean)

    是否生成用来记录对应操作的操作人信息,默认为 true 。如果允许生成的话,会生成 <prefix><operation><suffix> 字段,默认为 bigint 类型。

    • <prefix>: 前缀,由可选参数 :operator_prefix 提供,如果没有的话则使用默认值。

    • <operation>: 字段本体名称,即参数 fields 中给出的具体每个字段的名称本体。

    • <suffix>: 后缀,由可选参数 :operator_suffix 提供,如果没有的话则使用默认值。

  • :timestamp_prefix (String)

    操作时间字段前缀,默认为 nil

  • :timestamp_suffix (String)

    操作时间字段后缀,默认为 ‘_at’

  • :with_timestamp (Boolean)

    是否生成用来记录对应操作的时间戳信息,默认为 true 。如果允许生成的话,会生成 <prefix><operation><suffix> 字段,默认为 datetime 类型。

    • <prefix>: 前缀,由可选参数 :timestamp_prefix 提供,如果没有的话则使用默认值。

    • <operation>: 字段本体名称,即参数 fields 中给出的具体每个字段的名称本体。

    • <suffix>: 后缀,由可选参数 :timestamp_suffix 提供,如果没有的话则使用默认值。



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/activemodel_object_info/table_definition.rb', line 39

def operation_columns(*fields, **options)
  # puts "operation_columns(#{fields}, #{options})"
  # 初始化设置选项
  with_operator = options[:with_operator].nil? ? true : options[:with_operator]
  with_timestamp = options[:with_timestamp].nil? ? true : options[:with_timestamp]
  operator_prefix = options[:operator_prefix]
  operator_suffix = options[:operator_suffix] || '_by'
  timestamp_prefix = options[:timestamp_prefix]
  timestamp_suffix = options[:timestamp_suffix] || '_at'
  # 依照每个字段进行设置
  fields.each do |field|
    # 如果要生成操作人信息
    if with_operator
      operator_column_name = operator_prefix.to_s + field.to_s + operator_suffix.to_s
      column(operator_column_name, :bigint, index: true, comment: '操作人') if operator_column_name.present?
    end
    # 如果要生成操作时间戳信息
    if with_timestamp
      timestamp_column_name = timestamp_prefix.to_s + field.to_s + timestamp_suffix.to_s
      column(timestamp_column_name, :datetime, index: true, comment: '操作时间戳') if timestamp_column_name.present?
    end
  end
end