rails-erd icon indicating copy to clipboard operation
rails-erd copied to clipboard

Relationship not handling ThroughReflection correctly

Open gorj-tessella opened this issue 5 years ago • 0 comments

When dividing reflected associations into relationships there is some incorrect handling in determining the direction of the Relationship. Specifically, the code is relying on belongs_to? to determine if an ActiveRecord::AssociationReflection is a reverse association. But this is incorrect: only a BelongsToReflection has belongs_to? == true, but a ThroughReflection can have a @source_reflection which is a BelongsToReflection and is therefore a reverse association.

Thus these can end up incorrectly in the @forward_associations. Therefore when the code sets the source and destination based on the first of @forward_associations it can get it wrong if it picks up that ThroughReflection. cardinality and mutual? will also be directly affected by this, and indirect?should really be based on associations not just @forward_associations.

Example:

class A  < ActiveRecord::Base
  has_many :bs
end

class B < ActiveRecord::Base
  belongs_to :a
  has_many :cs
end

class C < ActiveRecord::Base
  belongs_to :b
  has_one :a, through: :b
end

The A/C relationship will have their sole association in @forward_associations and incorrectly identify the orientation of the relationship.

Relevant source:

https://github.com/voormedia/rails-erd/blob/0fbb1cdf2c84b06afd12974baace8d512bb798da/lib/rails_erd/domain/relationship.rb#L63-L71

partition_associations is generally based on belongs_to?

https://github.com/voormedia/rails-erd/blob/0fbb1cdf2c84b06afd12974baace8d512bb798da/lib/rails_erd/domain/relationship.rb#L147-L156

gorj-tessella avatar Jul 23 '19 21:07 gorj-tessella