Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

hyper-model reflects on associations of sibling STI class #275

Closed
adamcreekroad opened this issue Nov 4, 2019 · 0 comments
Closed

hyper-model reflects on associations of sibling STI class #275

adamcreekroad opened this issue Nov 4, 2019 · 0 comments

Comments

@adamcreekroad
Copy link
Contributor

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant