【问题标题】:mongoid update_attributes changed?mongoid update_attributes 改变了吗?
【发布时间】:2012-11-03 00:48:03
【问题描述】:

我想更新属性,然后检查信息是否更改

您可以在现有 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

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

【问题讨论】:

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


    【解决方案1】:

    它的完美逻辑。

    脏方法用于检查对象是否在保存之前发生了变化。根据定义,持久化对象没有待处理的更改。

    你应该这样做:

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

    See method definition.

    【讨论】:

    • 我试图用 ActiveRecord 风格,使用 changed 和 changes 属性,它们分别产生空哈希和数组。然后我使用了assign_attributes,然后才报告了更改。所以对于 Mongoid,那部分是必需的。
    猜你喜欢
    • 2011-07-06
    • 1970-01-01
    • 2013-01-26
    • 1970-01-01
    • 2017-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-13
    相关资源
    最近更新 更多