【问题标题】:Rails 3 : Increment Manually a field with mongoidRails 3:使用 mongoid 手动增加字段
【发布时间】:2011-01-16 19:06:02
【问题描述】:

我从 rails3 中的 gem mongoid 开始。

我想知道如何手动增加包含整数的字段。

我尝试了很多方法,但没有一种效果很好。

我想知道这个动作是否可以在原子上下文中完成?

【问题讨论】:

  • inc 函数是原子的,但不是线程安全的。

标签: ruby-on-rails-3 mongoid


【解决方案1】:

对于 Mongoid 4 之前的版本

从 mongoid 文档中,假设 Person 模型的 Integer 字段为“score”,这会将分数增加 100:

person = Person.find(id)
person.inc(score: 100) # Increment score    

更多信息:http://mongoid.org/en/mongoid/docs/persistence.html#atomic

【讨论】:

【解决方案2】:

Mongoid 4.0+的正确答案

person = Person.find(id)
person.inc(score: 100)

【讨论】:

  • 取决于您使用的 mongoid 版本。您的答案适用于 4.0+,但不适用于早期版本。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多