2

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

Sam J
  • 75
  • 1
  • 5
  • In my own limited experience with single table inheritance, the relationships still need to be defined on the model being inheited from. It's the methods you define, ie scope, enums, instance method that you can change on each model. But the relationships need to be on the model that has a table in the db. I may be wrong but that's what I had to do when I started playing with single table inheritance – Int'l Man Of Coding Mystery Jun 25 '19 at 13:09
  • I will give this a try. Would love to hear any advice others might have. – Sam J Jun 25 '19 at 13:23
  • Same ^, my experience is literally from one attempt. I just threw stuff at the wall and saw what stuck while tracing the errors, lol – Int'l Man Of Coding Mystery Jun 25 '19 at 13:42
  • 2
    I've solved it. There was a method contained within a concern with the same name as the association. That method was getting called. Oops! So it turns out you can define the associations on the child model after all – Sam J Jun 25 '19 at 13:51
  • Oh nice! Congratz! And thanks for letting me know. Will definitely help in refactoring for me in the future :D – Int'l Man Of Coding Mystery Jun 25 '19 at 14:00

0 Answers0