Home > Net >  Can someone explain me why I can't use in model two has_many through?
Can someone explain me why I can't use in model two has_many through?

Time:01-25

I am new at Ruby on Rails. And I do not understand, why there are can be only one has_many through in model?

class Physician < ApplicationRecord
  has_many :appointments
  has_many :patients, through: :appointments
  has_many :diagnoses
  has_many :patients, through: :diagnoses

end

class Appointment < ApplicationRecord
  belongs_to :physician
  belongs_to :patient
end

class Diagnosis < ApplicationRecord
  belongs_to :physician
  belongs_to :patient
end

class Patient < ApplicationRecord
  has_many :appointments
  has_many :physicians, through: :appointments
  has_many :diagnoses
  has_many :physicians, through: :diagnoses
end

CodePudding user response:

In Rails the assocations macros (belongs_to, has_one, has_many and has_and_belongs_to_many) write an AssocationReflection which contains all the metadata about the assocation which is kept in a hash as a class attribute.

The name of the assocation is the key used to store the reflection. When you declare multiple assocations with the same name you're just overwriting the previous assocation - this can actually be useful for example when inheriting the assocation or when monkeypatching.

In older versions of Rails redefining a has_many through: assocation can raise an HasManyThroughOrderError due to a flaw in the implementation which was fixed in 2018 and backported.

What you really should be doing is to define unique names for each assocation.

class Physician < ApplicationRecord
  has_many :appointments
  has_many :patients, through: :appointments
  has_many :diagnosed_patients, 
    through: :diagnoses,
    source:  :patient
end

class Patient < ApplicationRecord
  has_many :appointments
  has_many :physicians, through: :appointments
  has_many :diagnoses
  has_many :diagnosing_physicians, 
     through: :diagnoses,
     source:  :physicians
end
  •  Tags:  
  • Related