Class: Parse::RelationCollectionProxy

Inherits:
PointerCollectionProxy show all
Defined in:
lib/parse/model/associations/relation_collection_proxy.rb

Overview

The RelationCollectionProxy is similar to a PointerCollectionProxy except that there is no actual "array" object in Parse. Parse treats relation through an intermediary table (a.k.a. join table). Whenever a developer wants the contents of a collection, the foreign table needs to be queried instead. In this scenario, the parse_class: initializer argument should be passed in order to know which remote table needs to be queried in order to fetch the items of the collection.

Unlike managing an array of Pointers, relations in Parse are done throug atomic operations, which have a specific API. The design of this proxy is to maintain two sets of lists, items to be added to the relation and a separate list of items to be removed from the relation.

Because this relationship is based on queryable Parse table, we are also able to not just get all the items in a collection, but also provide additional constraints to get matching items within the relation collection.

When creating a Relation proxy, all the delegate methods defined in the superclasses need to be implemented, in addition to :'key'_relation_query, which should return a Parse::Query object that is properly tied to the foreign table class related to this object column. Example, if an Artist has many Song objects, then the query to be returned by this method should be a Parse::Query for the class 'Song'. Because relation changes are separate from object changes, you can call save on a relation collection to send only its staged add and remove operations, through the owner's atomic relation operations.

Instance Attribute Summary collapse

Attributes inherited from CollectionProxy

#delegate, #key, #loaded, #parse_class

Instance Method Summary collapse

Methods inherited from PointerCollectionProxy

#as_json, #fetch, #fetch!

Methods inherited from CollectionProxy

#&, #+, #-, #==, #as_json, #count, #destroy!, #each, #empty?, #first, #flatten, #forward, #last, #loaded?, #map, #notify_will_change!, #parse_objects, #parse_pointers, #reload!, #reset!, #second, #select, #set_collection!, #to_a, #uniq, #uniq!, #|

Constructor Details

#initialize(collection = nil, delegate: nil, key: nil, parse_class: nil) ⇒ RelationCollectionProxy

Returns a new instance of RelationCollectionProxy.



49
50
51
52
53
# File 'lib/parse/model/associations/relation_collection_proxy.rb', line 49

def initialize(collection = nil, delegate: nil, key: nil, parse_class: nil)
  super
  @additions = []
  @removals = []
end

Instance Attribute Details

#additions ⇒ Object

The objects that have been newly added to this collection



47
48
49
# File 'lib/parse/model/associations/relation_collection_proxy.rb', line 47

def additions
  @additions
end

#removals ⇒ Array<Parse::Object>



47
# File 'lib/parse/model/associations/relation_collection_proxy.rb', line 47

attr_reader :additions, :removals

Instance Method Details

#<<(*list) ⇒ Object

See Also:



318
319
320
321
# File 'lib/parse/model/associations/relation_collection_proxy.rb', line 318

def <<(*list)
  list.each { |d| add(d) }
  @collection
end

#add(parse_object) ⇒ Array<Parse::Object> #add(parse_objects) ⇒ Array<Parse::Object> Also known as: push

Add Parse::Objects to the relation. The change is staged and sent with the next save of the owner. Staging does not query the relation. Adding an item that is already staged has no further effect.

Overloads:

Returns:

Raises:

  • (ArgumentError) —

    if an item is nil, of another Parse class, or cannot be turned into a pointer.



122
123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/parse/model/associations/relation_collection_proxy.rb', line 122

def add(*items)
  items = typecast_items(items)
  return @collection if items.empty?

  notify_will_change!
  additions_will_change!
  removals_will_change!
  items.each do |item|
    @additions.push(item) unless @additions.include?(item)
    @removals.delete(item)
    @collection.push(item) if @loaded && !@collection.include?(item)
  end
  @collection
end

#add!(*items) ⇒ Boolean

Atomically add a set of Parse::Objects to this relation. This is done by making the API request directly with Parse server. On success the loaded collection includes the items, and a staged removal of the same items is dropped so a later save does not undo it. On an owner that has not been saved yet the items are staged as in #add and sent with the next save.

Returns:

  • (Boolean) —

    whether the operation succeeded.



200
201
202
203
204
205
206
207
208
209
210
211
# File 'lib/parse/model/associations/relation_collection_proxy.rb', line 200

def add!(*items)
  return false unless @delegate.respond_to?(:op_add_relation!)
  items = typecast_items(items)
  return true if items.empty?
  return add(*items) && true unless owner_persisted?
  return false unless @delegate.send(:op_add_relation!, @key, items.parse_pointers)
  items.each do |item|
    @removals.delete(item)
    @collection.push(item) if @loaded && !@collection.include?(item)
  end
  true
end

#add_unique(*items) ⇒ Object Also known as: push_unique

Same as #add: a relation never holds an object twice.



140
141
142
# File 'lib/parse/model/associations/relation_collection_proxy.rb', line 140

def add_unique(*items)
  add(*items)
end

#add_unique!(*items) ⇒ Object

See Also:



214
215
216
# File 'lib/parse/model/associations/relation_collection_proxy.rb', line 214

def add_unique!(*items)
  add!(*items)
end

#all(constraints = {}, &block) ⇒ Object

You can get items within the collection relation filtered by a specific set of query constraints.



73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/parse/model/associations/relation_collection_proxy.rb', line 73

def all(constraints = {}, &block)
  # An unsaved owner has no relation on the server yet.
  unless owner_saved?
    return block_given? ? collection.each(&block) : collection
  end
  q = query({ limit: :max }.merge(constraints))
  if block_given?
    # if we have a query, then use the Proc with it (more efficient)
    return q.present? ? q.results(&block) : collection.each(&block)
  end
  # if no block given, get all the results
  q.present? ? q.results : collection
end

#changes_applied! ⇒ Object

Marks the staged additions and removals as saved. Called after the owner is saved successfully, so the operations are not sent again by a later save.



239
240
241
242
243
# File 'lib/parse/model/associations/relation_collection_proxy.rb', line 239

def changes_applied!
  @additions = []
  @removals = []
  super
end

#clear ⇒ Array<Parse::Object>

Stage the removal of every object in the relation. This loads the relation to know what to remove.

Returns:



176
177
178
179
# File 'lib/parse/model/associations/relation_collection_proxy.rb', line 176

def clear
  remove(*collection.to_a)
  @collection
end

#clear_changes! ⇒ Object

Drops the staged additions and removals and clears the dirty tracking, without sending anything. When operations were staged, the items are reloaded from the server on the next access, since the loaded list included them.



265
266
267
268
269
270
271
272
# File 'lib/parse/model/associations/relation_collection_proxy.rb', line 265

def clear_changes!
  staged = staged_changes?
  @additions = []
  @removals = []
  super
  reset! if staged
  @collection
end

#collection ⇒ Array<Parse::Object>

The items of the relation. The first access queries the server for the related objects, then applies the additions and removals that have not been saved yet. An owner without an objectId has nothing on the server, so no query is sent for it.

Returns:



60
61
62
63
64
65
66
67
68
69
# File 'lib/parse/model/associations/relation_collection_proxy.rb', line 60

def collection
  unless @loaded
    fetched = owner_saved? ? forward(:"#{@key}_fetch!") : nil
    list = fetched.to_a.reject { |item| @removals.include?(item) }
    @additions.each { |item| list.push(item) unless list.include?(item) }
    @collection = list
    @loaded = true
  end
  @collection
end

#limit(count) ⇒ Object

Return a query with limit applied - allows chaining like relation.limit(5).all



106
107
108
# File 'lib/parse/model/associations/relation_collection_proxy.rb', line 106

def limit(count)
  query(limit: count)
end

#query(constraints = {}) ⇒ Object

Ask the delegate to return a query for this collection type



88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/parse/model/associations/relation_collection_proxy.rb', line 88

def query(constraints = {})
  q = forward :"#{@key}_relation_query"

  # Apply constraints if provided (excluding limit which is handled differently)
  query_constraints = constraints.except(:limit)
  if query_constraints.present?
    q = q.where(query_constraints)
  end

  # Apply limit if specified
  if constraints[:limit].present?
    q = q.limit(constraints[:limit])
  end

  q
end

#remove(parse_object) ⇒ Array<Parse::Object> #remove(parse_objects) ⇒ Array<Parse::Object> Also known as: delete

Removes Parse::Objects from the relation. The change is staged and sent with the next save of the owner. Staging does not query the relation.

Overloads:

Returns:



155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# File 'lib/parse/model/associations/relation_collection_proxy.rb', line 155

def remove(*items)
  items = typecast_items(items, strict: false)
  return @collection if items.empty?
  notify_will_change!
  additions_will_change!
  removals_will_change!
  # An unsaved owner has nothing on the server to remove.
  saved = owner_saved?
  items.each do |item|
    @removals.push(item) if saved && !@removals.include?(item)
    @additions.delete(item)
    @collection.delete(item)
  end
  @collection
end

#remove!(*items) ⇒ Boolean

Atomically remove a set of Parse::Objects from this relation. This is done by making the API request directly with Parse server. On success the items leave the loaded collection, and a staged addition of the same items is dropped.

Returns:

  • (Boolean) —

    whether the operation succeeded.



223
224
225
226
227
228
229
230
231
232
233
234
# File 'lib/parse/model/associations/relation_collection_proxy.rb', line 223

def remove!(*items)
  return false unless @delegate.respond_to?(:op_remove_relation!)
  items = typecast_items(items, strict: false)
  return true if items.empty?
  return remove(*items) && true unless owner_persisted?
  return false unless @delegate.send(:op_remove_relation!, @key, items.parse_pointers)
  items.each do |item|
    @additions.delete(item)
    @collection.delete(item)
  end
  true
end

#replace(items) ⇒ self

Stage the changes that make the relation hold exactly items.

Returns:

  • (self)


183
184
185
186
187
188
189
190
191
# File 'lib/parse/model/associations/relation_collection_proxy.rb', line 183

def replace(items)
  items = typecast_items(Array(items.is_a?(Parse::CollectionProxy) ? items.to_a : items))
  current = collection.to_a
  stale = current.reject { |item| items.include?(item) }
  remove(*stale) if stale.any?
  fresh = items.reject { |item| current.include?(item) }
  add(*fresh) if fresh.any?
  self
end

#rollback! ⇒ Object

Drops the staged additions and removals. The items are reloaded from the server on the next access.



247
248
249
250
251
252
253
# File 'lib/parse/model/associations/relation_collection_proxy.rb', line 247

def rollback!
  super
  @additions = []
  @removals = []
  reset!
  @collection
end

#save(session: SESSION_UNSET) ⇒ Boolean

Sends the staged additions and removals of this relation without saving the rest of the owner. The owner must already be saved: an unsaved owner sends its relation additions when it is created.

Removals and additions go out as two requests, removals first (each through the owner's atomic relation operation, so Parse::Role cache invalidation still runs). The two are not atomic: if the removals succeed and the additions fail, the removals stay applied, they are no longer staged, and the additions stay staged for a retry. An owner save sends relation changes the same way.

The requests use the owner's session token from its last save(session:), or the client's default credentials. Pass session: to send them as a specific user (a session token String or a User), or session: nil to send them with no session token.

Parameters:

  • session (String, Parse::User, nil) (defaults to: SESSION_UNSET) —

    the session to send the operations with, when given.

Returns:

  • (Boolean) —

    whether the staged operations were applied. False when the owner is not saved yet or a request failed; operations that did not succeed stay staged.



294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
# File 'lib/parse/model/associations/relation_collection_proxy.rb', line 294

def save(session: SESSION_UNSET)
  return true if @additions.empty? && @removals.empty?
  return false unless owner_persisted?
  return false unless @delegate.respond_to?(:op_add_relation!) && @delegate.respond_to?(:op_remove_relation!)
  applied = with_owner_session(session) do
    if @removals.any?
      next false unless @delegate.send(:op_remove_relation!, @key, @removals.parse_pointers)
      @removals = []
    end
    if @additions.any?
      next false unless @delegate.send(:op_add_relation!, @key, @additions.parse_pointers)
      @additions = []
    end
    true
  end
  return false unless applied
  clear_changes_information
  if @delegate.respond_to?(:clear_attribute_changes, true)
    @delegate.send(:clear_attribute_changes, [@key.to_s])
  end
  true
end

#staged_changes? ⇒ Boolean

Returns true when additions or removals are staged and not yet sent.

Returns:

  • (Boolean) —

    true when additions or removals are staged and not yet sent.



257
258
259
# File 'lib/parse/model/associations/relation_collection_proxy.rb', line 257

def staged_changes?
  @additions.any? || @removals.any?
end