Module: Mongoid::Persistable::Pushable
Relationships & Source Files | |
Extension / Inclusion / Inheritance Descendants | |
Included In:
| |
Super Chains via Extension / Inclusion / Inheritance | |
Class Chain:
self,
ActiveSupport::Concern
|
|
Defined in: | lib/mongoid/persistable/pushable.rb |
Overview
Defines behavior for $push and $addToSet operations.
Instance Method Summary
-
#add_to_set(adds) ⇒ Document
Add the single values to the arrays only if the value does not already exist in the array.
-
#push(pushes) ⇒ Document
Push a single value or multiple values onto arrays.
Instance Method Details
#add_to_set(adds) ⇒ Document
Add the single values to the arrays only if the value does not already exist in the array.
# File 'lib/mongoid/persistable/pushable.rb', line 20
def add_to_set(adds) prepare_atomic_operation do |ops| process_atomic_operations(adds) do |field, value| existing = send(field) || attributes[field] if existing.nil? attributes[field] = [] # Read the value out of attributes: # https://jira.mongodb.org/browse/MONGOID-4874 existing = attributes[field] end values = [ value ].flatten(1) values.each do |val| existing.push(val) unless existing.include?(val) end ops[atomic_attribute_name(field)] = { "$each" => values } end { "$addToSet" => ops } end end
#push(pushes) ⇒ Document
Push a single value or multiple values onto arrays.
# File 'lib/mongoid/persistable/pushable.rb', line 51
def push(pushes) prepare_atomic_operation do |ops| process_atomic_operations(pushes) do |field, value| existing = send(field) || begin attributes[field] ||= [] attributes[field] end values = [ value ].flatten(1) values.each{ |val| existing.push(val) } ops[atomic_attribute_name(field)] = { "$each" => values } end { "$push" => ops } end end