Rails 多态有很多通过

Rails 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

我需要能够双向查询,例如:

a) Podcast.first.topics #=> [主题 1、主题 2 等]

b) Topic.first.podcasts #=> [播客 1、播客 2 等]

我尝试了几种方法,但 none 中的方法工作正常。有人可以帮忙吗?

好的,我明白了:

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

现在我可以查询@podcast.topics和@topic.podcasts等