puchu
puchu

Reputation: 3652

mongoid update_attributes changed?

I want to update_attributes and than check if information is changed

You can simply pass this code to rails console in existing rails + mongoid project

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

Am I doing something wrong or this is a bug?

Upvotes: 3

Views: 4231

Answers (1)

apneadiving
apneadiving

Reputation: 115521

Its perfectly logic.

Dirty methods are meant to be used to check if an object has changed before it's saved. By definition a persisted object has no pending changes.

You should do:

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

See method definition.

Upvotes: 9

Related Questions