mongoid update_attributes改变了吗?

时间:2012-11-14 14:00:01

标签: ruby-on-rails ruby mongodb activerecord mongoid

我想更新update_attributes,而不是检查信息是否已更改

您只需将此代码传递给现有rails + mongoid项目中的rails console

即可
class TestModel
  include Mongoid::Document
  include Mongoid::Timestamps
  field :name, type: String
end

test = TestModel.new({:name => "name 1"})
test.save()
=> true

test
=> created_at: 2012-11-14 13:48:26 UTC, updated_at: 2012-11-14 13:48:26 UTC

test.changed?
=> false
test.name_changed?
=> false

test.update_attributes({:name => "name 2"})
=> true

test.changed?
=> false
test.name_changed?
=> false

test
=> created_at: 2012-11-14 13:48:26 UTC, updated_at: 2012-11-14 13:49:23 UTC

我做错了什么或这是一个错误?

1 个答案:

答案 0 :(得分:8)

完全合乎逻辑。

脏方法用于检查对象是否已经更改保存之前。根据定义,持久化对象没有挂起的更改。

你应该这样做:

test.assign_attributes(attributes)
test.changed? #=> true
test.save

See method definition