This problem involves a rails ActiveRecord many-to-many association and a case of single-table-inheritance. I am struggling to get the association Patient
-> Membership
to work. All other associations work as expected.
Note that Member
(below) contains foreign key fields for membership_id
and patient_id
.
So far I have experimented with various combinations of options for the associations but haven't managed to find the correct setup to make the association work
class LineItem < ApplicationRecord
end
class Membership < LineItem
has_many :members, dependent: :destroy, foreign_key: :line_item_id, inverse_of: :membership
has_many :patients, through: :members
end
class Member < ApplicationRecord
belongs_to :membership, foreign_key: :line_item_id, inverse_of: :members
belongs_to :patient, optional: true
end
class Patient < ApplicationRecord
has_many :members
has_many :memberships, through: :members
end
Let patient_1
be an instance of Patient
.
Let membership_1
be an instance of Membership
.
Let them be associated through member_1
, an instance of Member
.
I would expect patient_1.memberships
to return membership_1
(contained within ActiveRecord Relation).
Instead I am getting the following error:
ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR: column line_items.member_id does not exist