Skip to content

Instantly share code, notes, and snippets.

@tcwalther
Created October 17, 2014 16:27
Show Gist options
  • Save tcwalther/d545d45466cc4660fe27 to your computer and use it in GitHub Desktop.
Save tcwalther/d545d45466cc4660fe27 to your computer and use it in GitHub Desktop.
# the data model is based on
# http://railscasts.com/episodes/154-polymorphic-association-revised
class Article < ActiveRecord::Base
has_many :comments, as: :commentable
# example for a custom function that is always the same for each "commentable"
def most_important_comment
comments.first
end
end
class Post < ActiveRecord::Base
has_many :comments, as: :commentable
# example for a custom function that is always the same for each "commentable"
def most_important_comment
comments.first
end
end
class Comment < ActiveRecord::Base
belongs_to :commentable, polymorphic: true
end
###################
# I would like to group common behaviour, either by inheritance, or via Ruby mixins
# Using Modules
module Commentable
# this will break saying "has_many" is not defined
# I can
# include ActiveRecord::Associations
# but that will then crash saying "undefined method `dangerous_attribute_method?`"
has_many :comments, as: :commentable
# example for a custom function that is always the same for each "commentable"
def most_important_comment
comments.first
end
end
class Article
include Commentable
end
class Post
include Commentable
end
class Comment < ActiveRecord::Base
belongs_to :commentable, polymorphic: true
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment