Skip to content

Instantly share code, notes, and snippets.

@alexgriff
Last active March 30, 2016 23:28
Show Gist options
  • Save alexgriff/1318c6d76014ee450a8696e88e79519d to your computer and use it in GitHub Desktop.
Save alexgriff/1318c6d76014ee450a8696e88e79519d to your computer and use it in GitHub Desktop.
# Voter, the polymorphic model
class Voter < ActiveRecord::Base
belongs_to :voterable, polymorphic: true
has_many :votes
has_many :candidates, through: :votes
end
# Citizen, has one voter as voterable
# this is a new model where many of the attributes
# that a voter has would move to
class Citizen < ActiveRecord::Base
has_one :voter, as: :voterable
end
# Candidate, has one voter as voterable
# this was interesting, I wasn't sure if ActiveRecord would allow a model to
# have_many of a model and have_one of the same model. Turns out it can.
# candidate.voters will be a method as well as a candidate.voter
#
# I added a method #as_a_voter, which aliases the #voter method
# that ActiveRecord provides to, hopefully, lessen confusion and
# make the interface more legible
class Candidate < ActiveRecord::Base
has_one :voter, as: :voterable
has_many :votes
has_many :voters, through: :votes
def as_a_voter
self.voter
end
end
# Vote, nothing here has changed
class Vote < ActiveRecord::Base
belongs_to :voter
belongs_to :candidate
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment