Yasin Shuman
Yasin Shuman

Reputation: 137

updating postgres table using gorm

I'm having trouble trying to update rows in my table. I have tried the following:

return ss.db.Where("name = ?", sub.Name).Save(&sub).Error

and

return ss.db.Save(sub).Error

I've also tried variations of this

s := ss.db.Where("Name = ?", sub.Name)
    return ss.db.Model(&s).Updates(Subscription{Name: sub.Name, DevicesAllowed: sub.DevicesAllowed, Price: sub.Price, Active: sub.Active}).Error

I have also tried several other approaches that havent worked, for example, this attempt results in all the rows being changed:

return ss.db.Model(&sub).Updates(Subscription{Name: sub.Name, DevicesAllowed: sub.DevicesAllowed, Price: sub.Price, Active: sub.Active}).Error

I have the rest of the code here in a gist for reference: https://gist.github.com/yshuman1/8a26a90507bc13de7290d3adc0facdd1

Any help or advice would be appreciated! Thank you.

Upvotes: 1

Views: 270

Answers (1)

Yasin Shuman
Yasin Shuman

Reputation: 137

the solution was to find the record int he table and then replace the old values with the new ones prior to using .Save() like this:

func (ss *SubscriptionService) Update(sub *Subscription) error {
    var subscription Subscription
    db := ss.db.Where(&Subscription{Name: sub.Name})
    err := first(db, &subscription)
    if err != nil {
        log.Error("error looking up subscription")
        return err
    }
    subscription.Price = sub.Price
    subscription.Active = sub.Active
    subscription.DevicesAllowed = sub.DevicesAllowed
    return ss.db.Save(&subscription).Error
}

Upvotes: 1

Related Questions