Skip to content

Automatically create inverse relationship as needed #89

Closed
@catmando

Description

@catmando

currently hyper-model requires that for the both sides of the belongs_to and has_many relationships are explicitly declared.

Seems like the following patch fixes that:

module ActiveRecord
  module Associations
    class AssociationReflection
      def find_inverse
        klass.reflect_on_all_associations.each do |association|
          next if association.association_foreign_key != @association_foreign_key
          next if association.klass != @owner_class
          next if association.attribute == attribute
          return association if klass == association.owner_class
        end
        if macro == :belongs_to
          Hyperstack::Component::IsomorphicHelpers.log "**** warning dynamically adding relationship: #{klass}.has_many :#{@owner_class.name.underscore.pluralize}, foreign_key: #{@association_foreign_key}", :warning
          klass.has_many @owner_class.underscore.pluralize, foreign_key: @association_foreign_key
        else
          Hyperstack::Component::IsomorphicHelpers.log "**** warning dynamically adding relationship: #{klass}.belongs_to :#{@owner_class.name.underscore}, foreign_key: #{@association_foreign_key}", :warning
          klass.belongs_to @owner_class.underscore, foreign_key: @association_foreign_key
        end
        # raise "Association #{@owner_class}.#{attribute} "\
        #       "(foreign_key: #{@association_foreign_key}) "\
        #       "has no inverse in #{@klass_name}"
      end
    end
  end
end

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or requestready-to-releaseInternal Use Only: Has been fixed, specs passing and pushed to edge branch

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions