1

I'm trying to do the following but getting a bit confused about how to setup the polymorphic has many through.

Class Topic

end


Class Post
    

end


Class Podcast

end


Class ResourceTopics

    # This table has the following fields: [topical_type, topical_id]


end

I need to be able to query both ways so for example:

a) Podcast.first.topics #=> [Topic 1, Topic 2, etc]

b) Topic.first.podcasts #=> [Podcast 1, Podcast 2, etc]

I have tried several ways but none of which are working correctly. Can someone please help?

3
  • guides.rubyonrails.org/association_basics.html , just add belongs_to , etc associations as per your requirement. Commented Sep 23, 2021 at 7:42
  • @CandyCrunch Thats not enough, I need a Podcast to belong to a Topic through Resource Topics and Resource Topics needs to be polymorphic since its not just podcasts that can have topics, posts can to. Commented Sep 23, 2021 at 7:44
  • I would say you need to define 2 different has_many :through associations and for each you specify the class. Commented Sep 23, 2021 at 8:33

1 Answer 1

2

Ok, I figured it out:

Class Topic
    has_many :resource_topics
    has_many :podcasts, through: :resource_topics, source: :topical, source_type: 'Podcast'
    has_many :courses, through: :resource_topics, source: :topical, source_type: 'Course'
end


Class Course
    has_many :resource_topics, as: :topical
    has_many :topics, through: :resource_topics
end


Class Podcast
    has_many :resource_topics, as: :topical
    has_many :topics, through: :resource_topics
end


Class ResourceTopics

    # This table has the following fields: [topical_type:string, topical_id:integer]

    belongs_to :topic
    belongs_to :topical, polymorphic: true
end

Now I can query @podcast.topics and @topic.podcasts etc

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.