granite
granite copied to clipboard
Are STIs supported?
Crystal's inherited
hook is called even when inheriting child is inherited. So when we have an STI model like so, the inherited hook is called twice.
class Animal < Granite::ORM::Base
macro inherited
puts "inherited macro called"
end
end
class Dog < Animal
end
class Cat < Animal
end
In Granite, the validators.cr
uses the inherited hook to define @@validators
.
macro inherited
@@validators = Array({field: Symbol, message: String, block: Proc(self, Bool)}).new
end
However when we define a new child model, granite tries to create @@validators
again and fails because Crystal cannot reinitialize a class var.
Is there a workaround for this? Thanks for your effort.
@notalex yes. @faustinoaq fixed this in his last PR. 🥇 We removed the class var. I will release Granite soon or you can try the master branch.
Are there any updates on this? I have seem to be having the same problems - I'm on version 0.15.2, which as far as I am aware appears to be the latest
@johansenja This will be fixed in #346.
abstract class Animal < Granite::Base
column id : Int64, primary: true
column color : String
column breed : String
end
class Dog < Animal
table dogs
column dog_column : String
end
class Cat < Animal
table cats
column cat_column : String
end
Dog.new
#<Dog:0x7f49e4a59f00
@_current_callback=nil,
@breed=nil,
@color=nil,
@destroyed=false,
@dog_column=nil,
@errors=[],
@id=nil,
@new_record=true>
Cat.new
#<Cat:0x7f49e4a59e60
@_current_callback=nil,
@breed=nil,
@cat_column=nil,
@color=nil,
@destroyed=false,
@errors=[],
@id=nil,
@new_record=true>
It will at least not error on you. However I wouldn't call this STI in that there would have to be some extra work to support automatically settings a discriminator.
Actually after looking into the issue more it's a bit more involved than I thought. My fix then causes some other issues when actually using the validations.
I'm going to save this for another PR at some point if I think of another option.
Closing this out, but keeping the other RFC issue about changing how validations work since that's the core issue