Method: Dynamoid::Persistence#save
- Defined in:
- lib/dynamoid/persistence.rb
#save(options = {}) ⇒ true|false
Create new model or persist changes.
Run the validation and callbacks. Returns true if saving is successful and false otherwise.
user = User.new
user.save # => true
user.age = 26
user.save # => true
Validation can be skipped with validate: false option:
user = User.new(age: -1)
user.save(validate: false) # => true
save by default sets timestamps attributes - created_at and updated_at when creates new model and updates updated_at attribute when updates already existing one.
Changing updated_at attribute at updating a model can be skipped with touch: false option:
user.save(touch: false)
If a model is new and hash key (id by default) is not assigned yet it was assigned implicitly with random UUID value.
If lock_version attribute is declared it will be incremented. If it’s blank then it will be initialized with 1.
save method call raises Dynamoid::Errors::RecordNotUnique exception if primary key (hash key + optional range key) already exists in a table.
save method call raises Dynamoid::Errors::StaleObjectError exception if there is lock_version attribute and the document in a table was already changed concurrently and lock_version was consequently increased.
Raises Dynamoid::Errors::MissingHashKey if a model is already persisted and a partition key has value nil and raises Dynamoid::Errors::MissingRangeKey if a sort key is required but has value nil.
When a table is not created yet the first save method call will create a table. It’s useful in test environment to avoid explicit table creation.
567 568 569 570 571 572 573 574 575 576 577 578 579 |
# File 'lib/dynamoid/persistence.rb', line 567 def save( = {}) if Dynamoid.config.create_table_on_save self.class.create_table(sync: true) end create_or_update = new_record? ? :create : :update run_callbacks(:save) do run_callbacks(create_or_update) do Save.call(self, touch: [:touch]) end end end |