Closed
Description
This is only an issue when using STI classes that have their own associations.
An example:
class Owner < ApplicationRecord
has_many :pets
end
class Bone < ApplicationRecord
belongs_to :dog
end
class ScratchingPost < ApplicationRecord
belongs_to :cat
end
class Pet < ApplicationRecord
belongs_to :owner
end
class Dog < Pet
has_many :bones
end
class Cat < Pet
has_many :scratching_posts
end
Pet.reflect_on_all_associations
# Currently
#=> [{ belongs_to: :owner, ... }, { has_many: :bones, ... }, { has_many: :scratching_posts, ... }]
# Should be
#=> [{ belongs_to: :owner, ... }]
Dog.reflect_on_all_associations
# Currently
#=> [{ belongs_to: :owner, ... }, { has_many: :bones, ... }, { has_many: :scratching_posts, ... }]
# Should be
#=> [{ belongs_to: :owner, ... }, { has_many: :bones, ... }]
Cat.reflect_on_all_associations
# Currently
#=> [{ belongs_to: :owner, ... }, { has_many: :bones, ... }, { has_many: :scratching_posts, ... }]
# Should be
#=> [{ belongs_to: :owner, ... }, { has_many: :scratching_posts, ... }]
The code that is doing this is
def self.reflect_on_all_associations
base_class.instance_eval { @associations ||= superclass.instance_eval { (@associations && @associations.dup) || [] } }
end
It always reflects on the base_class, so that and all the inheriting get all the associations. This causes issues where hyper-model is trying to instantiate associations on the client, but they don't exist on that class but maybe its sibling's class the an error is thrown and the page goes blank.
I'm thinking this was done before STI was implemented and the type
column was looked at and used. But since that has been implemented, this should be fixed so that only the proper associations are reflected on and used.
A fix would be
def self.reflect_on_all_associations
@associations ||= superclass.instance_eval { (@associations && @associations.dup) || [] }
end
Run locally, all specs pass.
Metadata
Metadata
Assignees
Labels
No labels