Skip to content

Instantly share code, notes, and snippets.

@jaeming
Created February 2, 2016 02:10
Show Gist options
  • Save jaeming/1c1eb9d9bb4a4b4a84c1 to your computer and use it in GitHub Desktop.
Save jaeming/1c1eb9d9bb4a4b4a84c1 to your computer and use it in GitHub Desktop.
# I was working on a client project not long back and the client expressed an interest in having thread-able comments, where someone can reply to one comment and it starts off a new thread of comments, which could then be branched even further by other replies. It occurred to me that I already had a polymorphic association with my comments so that different resources could be commented on (articles, photos, statuses, etc...). It seemed plausible I could just go ahead and use this on a self-referential basis as well.
# With polymorphic associations, instead of having a foreign key like, article_id, you have a type column representing the table and an id column for whatever type table that is. For instance:
:commendable_type => 'Article', :commendable_id => 1
# Would be comparable to a foreign key reference of
:article_id => 1
#thus polymorphic models can be associated with any other model type, including themselves it turns out.
:commendable_type => 'Comment'
# Represents a comment that belongs to a comment.
class Comment < ActiveRecord::Base
belongs_to :commentable, polymorphic: true
has_many :comments, as: :commentable
belongs_to :user
end
# So one way to have comment threads is simply to comment on a comment. This worked well. Go ahead and try it.
# it's another take on self-referential associations but without using alias classes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment