How to save a realm relationship (list)
<p>I've had try to save a realm object to my database, but it's not working.</p>

<p>Here's my models:</p>

<pre><code>class CreditCard: Object {
    dynamic var owner: String?
    var purchases: List&lt;Purchase&gt;()
}
</code></pre>

<p>And second class which looks like that:</p>

<pre><code>class Purchase: Object {
    dynamic var id: Int = 0
    dynamic var name: String?
    dynamic var data: String?
    let creditCard = LinkingObjects(fromType: CreditCard.self, property: "purchases")
}
</code></pre>

<p>I can save all CreditCard objects just fine.</p>

<p>On a second view controller, I have another request, to download all purchases made by a credit card. After the request this is how I try to write to realm:</p>

<pre><code>let creditCard = realm.objects(CreditCard.self).first // there's some code to get this. 
try! realm.write {
    for purchase in purchases { // purchases = objects from a son
        let newPurchase = Purchase()
        newPurchase.id = purchase["Id"].intValue
        newPurchase.name = purchase["name"].stringValue
        newPurchase.date = purchase["date"].dateValue

        creditCard.purchases.append(newPurchase)
        realm.add(creditCard, update: true)
    }
 }
</code></pre>

<p>For some reason all purchases objects are lost when the app closes. The purchases are saved on my realm objects, but the relationship between CreditCard and Purchase is lost. So, the return from the code below is always empty when I re-open the app:</p>

<pre><code>let purchases = creditCard.purchases
</code></pre>

<p>What am I doing wrong?</p>