From 794e1ba20b2161e0539fe813649df229929c6367 Mon Sep 17 00:00:00 2001 From: jnfeinstein Date: Tue, 25 Nov 2014 11:42:05 -0800 Subject: [PATCH] .Count() should always use ToSnake'd foreign keys. It looks like gorm always uses the snake form of a column by convention, as seen by searching DBName in scope.go. These counts were erroring out without the ToSnake'd foreign keys. Further, the code for has_many and has_one becomes the same (which makes sense), so I combined the two cases. --- association.go | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/association.go b/association.go index be6b1b35..86b586e4 100644 --- a/association.go +++ b/association.go @@ -170,15 +170,12 @@ func (association *Association) Count() int { relationship.JoinTable, scope.Quote(ToSnake(relationship.ForeignKey))) scope.db.Model("").Table(newScope.QuotedTableName()).Where(whereSql, association.PrimaryKey).Count(&count) - } else if relationship.Kind == "has_many" { + } else if relationship.Kind == "has_many" || relationship.Kind == "has_one" { whereSql := fmt.Sprintf("%v.%v = ?", newScope.QuotedTableName(), newScope.Quote(ToSnake(relationship.ForeignKey))) scope.db.Model("").Table(newScope.QuotedTableName()).Where(whereSql, association.PrimaryKey).Count(&count) - } else if relationship.Kind == "has_one" { - whereSql := fmt.Sprintf("%v.%v = ?", newScope.QuotedTableName(), relationship.ForeignKey) - scope.db.Model("").Table(newScope.QuotedTableName()).Where(whereSql, association.PrimaryKey).Count(&count) } else if relationship.Kind == "belongs_to" { if v, err := scope.FieldValueByName(association.Column); err == nil { - whereSql := fmt.Sprintf("%v.%v = ?", newScope.QuotedTableName(), relationship.ForeignKey) + whereSql := fmt.Sprintf("%v.%v = ?", newScope.QuotedTableName(), newScope.Quote(ToSnake(relationship.ForeignKey))) scope.db.Model("").Table(newScope.QuotedTableName()).Where(whereSql, v).Count(&count) } }