I'm experimenting with using Go to read from a database that's been part of an existing Rails app. A few of the models and therefore tables use single table inheritance via a type
column. In Rails/ActiveRecord, the presence of this column will create an automatic mapping to the appropriate model. If the table is animals
and type
is Dog
, it will map to the Dog
class; if it's Cat
, it'll map to the Cat
class. I want to setup something similar in Gorm.
Since it doesn't seem like Gorm has a default_scope
option for a model, I'm using a new callback.
func scopedSearch(scope *gorm.Scope) {
tablename := scope.TableName()
switch tablename {
case "table_using_sti":
scope.Search.Where("type = ?", "MyModelName")
default:
return
}
}
And then I register the callback in my main
function:
db.Callback().Query().Before("gorm:query").Register("my_plugin:before_query", scopedSearch)
When I search against an instance using db.First
or the model using db.Model(&MyModel{}).Where(...)
, it appears to be working. Is this the right way to handle it? Will this scope be respected by all of the query methods or is there something more direct or thorough?