Created
October 17, 2014 16:27
-
-
Save tcwalther/d545d45466cc4660fe27 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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