ActiveRecord - querying polymorphic associations

前端 未结 8 1366
深忆病人
深忆病人 2020-12-04 14:10

I am using polymorphic associations to track Comments in my project. All very straight forward stuff.

The problem I have is in querying based on the polymorphic asso

8条回答
  •  没有蜡笔的小新
    2020-12-04 14:45

    The accepted solution does not work once you introduce another model that has an association using "commentable". commentable_id is not unique and therefore you'll start retrieving the wrong comments.

    For example:

    You decide to add a news model that accepts comments...

    class News < ActiveRecord::Base
       has_many :comments, :as => :commentable
    end
    

    Now you may get two records back if you made a comment on a forum_topic with an id of 1 and a news article with an id of 1 using your query:

    :joins => "INNER JOIN forum_topics ON forum_topics.id = comments.commentable_id"
    

    You could probably solve the problem by supplying a commentable_type as one of your conditions, but I don't think that's the best way to approach this issue.

提交回复
热议问题