shlogg · Early preview
Augusts Bautra @augustsbautra

Filtering Comments By Post Data With Rails Associations

Filtering comments by post data with polymorphic associations. Use `has_one` and `through` to alleviate joining, or scope options for specific child types.

Let's say we have a model structure that allows us to make comments on anything:

Comment.has_one :comment_commentee_tie
CommentCommenteeTie
  belongs_to :comment
  belongs_to :commentee, polymorphic: true
Post
  has_many :comment_commentee_ties

    
    

    
    




Now let's say we want to filter comments by possible post data. To alleviate the joining, we can define a non-polymorphic association for Comment:

Comment
  has_one :comment_commentee_tie
  has_one :post, through: :comment_commentee_tie, source: :commentee, source_type: "Post"

    
    

    
    




  
  
  Polymorphic chi...