Brad
Brad

Reputation: 8668

Rails polymorphic has many through

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?

Upvotes: 1

Views: 75

Answers (1)

Brad
Brad

Reputation: 8668

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

Upvotes: 2

Related Questions