模块:Mongoid::Persistable::Settable

扩展方式:
ActiveSupport::Concern
包含在:
Mongoid::Persistable
定义于:
lib/mongoid/persistable/settable.rb

Overview

定义 $ 设立操作的行为。

实例方法摘要折叠

实例方法详细信息

# 设立 (setters) ⇒文档

对提供的字段/值对执行 $ 设立操作,并在内存中设立文档中的值。

键可以是键的虚线序列,在这种情况下,顶级字段被视为嵌套哈希,并自动创建任何缺失的键:

像这样执行嵌套设立合并中间键的值:

如果顶级字段不是哈希值,则丢弃其原始值,并将该字段替换为哈希值。

请注意,与 MongoDB 的 $ 设立不同,Mongoid 的设立会写出整个字段,即使通过嵌套哈希语义设置字段的子集也是如此。 这意味着使用嵌套哈希语义执行 $ 设立可以覆盖数据库顶级字段中的其他哈希键。

例子:

设置值。

document.set(title: "sir", dob: Date.new(1970, 1, 1))

使用嵌套哈希语义设置值。

document.set('author.title' => 'Sir')
# => document.author == {'title' => 'Sir'}

嵌套哈希值合并。

document.set('author.title' => 'Sir')
document.set('author.name' => 'Linus Torvalds')
# => document.author == {'title' => 'Sir', 'name' => 'Linus Torvalds'}

嵌套哈希覆盖非哈希值。

document.set('author' => 'John Doe')
document.set('author.title' => 'Sir')
# => document.author == {'title' => 'Sir'}

参数:

  • setter (哈希)

    要设置的字段/值对。

返回:



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/mongoid/persistable/settable.rb', line 48

def (setter)
  prepare_atomic_operation do |运维|
    process_atomic_operations(setter) do |字段, |

      field_seq = 字段.to_s.拆分('  ')
      字段 = field_seq.转变
      if field_seq.长度 > 0
        # 嵌套哈希路径
        old_value = 属性[字段]

        # 如果旧值不是哈希值,则破坏它
        除非 哈希 === old_value
          old_value = {}
        end

        # 深入哈希,根据需要创建中间键
        当前值 = old_value
        while field_seq.长度 > 1
          cur_key = field_seq.转变
          # 如果类型不是哈希,则在每个级别上进行破坏
          除非 哈希 === 当前值[cur_key]
            当前值[cur_key] = {}
          end
          当前值 = 当前值[cur_key]
        end

        # 现在我们处于叶级别,执行设立
        # 并覆盖之前此级别上的所有内容
        当前值[field_seq.转变] = 

        # 并将值设立为顶级字段的值
        # 因为这是我们传递给 $ 设立的内容
         = old_value
      end

      process_attribute(字段, )

      除非 关系.包括?(字段.to_s)
        运维[atomic_attribute_name(字段)] = 属性[字段]
      end
    end
    { " $set " => 运维 } 除非 运维.空?
  end
end