To add to the answer by Josh, sometimes you might want to share some code defining a polymorphic association. You can't just put the has_many method call in your module, because you will get an error, for example in a module called Votable:
undefined method `has_many' for Voteable:Module (NoMethodError)
So instead, you need to use the self.included(base) method and base.instance_eval. Here's an example with my Voteable module:
module Voteable
def self.included(base)
base.instance_eval do
has_many :votes, as: :voteable
has_many :voters, through: :votes
end
end
def voted_up_by?(user)
user and votes.exists?(value: 1, voter_id: user)
end
def voted_down_by?(user)
user and votes.exists?(value: -1, voter_id: user)
end
end
Now you can include Voteable in models that will have that behavior. This will execute the self.included(base) method and it will define the association on the including class.