granite icon indicating copy to clipboard operation
granite copied to clipboard

Are STIs supported?

Open notalex opened this issue 6 years ago • 4 comments

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 avatar Jan 27 '18 09:01 notalex

@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.

drujensen avatar Jan 27 '18 10:01 drujensen

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 avatar Apr 06 '19 12:04 johansenja

@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.

Blacksmoke16 avatar Jul 11 '19 12:07 Blacksmoke16

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.

Blacksmoke16 avatar Jul 12 '19 12:07 Blacksmoke16

Closing this out, but keeping the other RFC issue about changing how validations work since that's the core issue

crimson-knight avatar Apr 25 '23 12:04 crimson-knight