2012-11-14 44 views
2

我想,如果信息发生改变mongoid update_attributes已更改?

您可以将此代码简单地传递到rails console在现有的轨道+ mongoid项目

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 

我是不是做错了什么要和的update_attributes比检查或这是一个错误?

回答

8

它的完美逻辑。

脏方法是用来检查对象是否已经更改之前它被保存。根据定义,持久对象没有未决的更改。

你应该这样做:

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

See method definition

+0

我试图做到这一点ActiveRecord风格,使用改变和改变属性,他们分别产生空的哈希和数组。然后我使用了assign_attributes,然后才报告了变化。所以对于Mongoid来说,这个部分是必需的。 – Donato