wvteijlingen / Spine

A Swift library for working with JSON:API APIs. It supports mapping to custom model classes, fetching, advanced querying, linking and persisting.
MIT License
264 stars 109 forks source link

Create LinkedResourceCollection from single resource #147

Closed cmwall closed 7 years ago

cmwall commented 7 years ago

I have one resource that I would like to apply to a model inside of a has_many relationship.

My attribute is similar to var comments: LinkedResourceCollection? in a Post model.

I would like to create a new Post object and append an existing comment object to the comments attribute of the Post object.

I do not know how to instantiate a new LinkedResourceCollection and append a single attribute.

How can I do so?

wvteijlingen commented 7 years ago

If I understand correctly the comment already exists and is already linked to the post? In that case, you can just do this:

let collection = LinkedResourceCollection(resourcesURL: nil, linkURL: nil, linkage: nil)
collection.appendResource(comment)
post.comments = collection

If the comment is not linked to the post, and you like to link it, you can do the following:

let collection = LinkedResourceCollection(resourcesURL: nil, linkURL: nil, linkage: nil)
collection.linkResource(comment)
post.comments = collection

The initialisers are a little clumsy for this use case, I'll see if I can add some more initialisers that would make this more streamlined.

sachin-sat commented 7 years ago

@wvteijlingen
is it possible to save() an object(i mean PATCH update) to server without relationships. eg : A Person object has a relation called Comments. I would like to just re-name the name attribute of a person. name is a attribute of a model and comments is a to-many relationship with the model.

let person = Person.init(id:person_to_be_renamed) person.name = "wvteijlingen" spine.save(person)

is this possible? it crashes since there are no comments collection. tried omitNullValues too.

thanks in advance.

wvteijlingen commented 7 years ago

This doesn't work because Spine then overrides the relationship with null. You have to first fetch the person from the server so it has the correct relationship data.

cmwall commented 7 years ago

That worked @wvteijlingen , Thanks.