0

I would like to achieve something as follows where PersonSubject has many topics, but the choices of these topics are limited to the the selection of topics through another model (ie: through the associated subject):

class Topic < ApplicationRecord
  belongs_to :subject
end

class Subject < ApplicationRecord
  has_many :topics
end

class PersonSubject < ApplicationRecord
  belongs_to :person
  belongs_to :subject
  has_many :topics  # where the choices are limited to the subject.skills
end

I would then like if any person_subject.subject.topics are deleted (or association removed), it would automatically update the person_subject.topics to no longer "point" to the Topic(s) that were deleted.

Is this possible?

Arnoux
  • 226
  • 2
  • 9

1 Answers1

0

You can use a lambda to put arbitrary filters on an association. See What is the equivalent of the has_many 'conditions' option in Rails 4?

has_many :topics, -> { where(skill: subject.skills) }

I don't know that this is exact code will work without seeing your schema (what is the data type of subject.skills, and how do you join this with topic?). But hopefully this gets you on the right track

edit

in response to your comment, I think

has_many :topics, through: :skills

would work

max pleaner
  • 26,189
  • 9
  • 66
  • 118
  • Hey Max, I appreciate the help. Unfortunately I had made a typo the first time round, and had meant to write `topics` instead of `skills`. I figured I could do something like what you are saying, ie: limiting the `topics` of a `PersonSubject` record to those linked to by the associated `subject`, but I would also then like to know that removing any of the `subject.topics` for the `PersonSubject` record will actually update which `topics` are linked to from the `PersonSubject` record. – Arnoux Jun 18 '19 at 17:44
  • The problem with `through` is that it gives me all `topics` of the associated `subject`, whereas I would like to be able to set the `topics` of the `TutorSubject` record to be a subset of that of the `subject.topics` (or am I being silly? is there another way?) – Arnoux Jun 18 '19 at 19:50
  • @Arnoux I think you can combine the `has_many :through` with the lambda option in this case. How do you link Topic with PersonSubject? Each topic has a person_subject_id? – max pleaner Jun 18 '19 at 19:56
  • I was actually hoping to not have to have link the `Topic` back to `PersonSubject` at all. Perhaps what I am asking is not possible. – Arnoux Jun 18 '19 at 20:13
  • Can you share all relevant parts of your schema? – max pleaner Jun 18 '19 at 20:41