Active Records Associations

This guide teaches you how to associate multiple models.

How to use Active Records associations.

Chapters

  1. 1. Types of Associations
    1. 1.1. The BelongsTo Association
    2. 1.2. The HasOne Association
    3. 1.3. The HasMany Association

1. Types of Associations

1.1. The BelongsTo Association

Owner := activerecord.New("owner", func(r *activerecord.R) {
  r.BelongsTo("target")
})

If you want to access the associated record, use the Association method:

target := Owner.Association("target")
fmt.Println(target) // Ok(Some(<#Target id: 2, name: "Bill">))

1.2. The HasOne Association

Owner := activerecord.New("owner", func(r *activerecord.R) {
  r.HasOne("target")
})
target := Owner.Association("target")
fmt.Println(target) // Ok(Some(<#Target id: 4, owner_id: 5, name: "John"))

1.3. The HasMany Association

Owner := activerecord.New("owner", func(r *activerecord.R) {
  r.HasMany("targets")
})

If you want to access the collection of association records, use the Collection method:

targets := Owner.Collection("targets")
fmt.Println(targets.First()) // #<Target id: 3, owner_id: 1, name: "Elon">