Skip to content

Instantly share code, notes, and snippets.

Created July 14, 2009 09:20
Show Gist options
  • Save anonymous/146868 to your computer and use it in GitHub Desktop.
Save anonymous/146868 to your computer and use it in GitHub Desktop.
module War
class War::Character
include DataMapper::Resource
property :id, Serial
# ...
has n, :raid_participations, :class_name => 'War::RaidParticipants'
has n, :raids, :class_name => 'War::Raid', :through => :raid_participations, :child_key => [:character_id]
before :destroy do
raid_participations.destroy!
end
end
class Raid
include DataMapper::Resource
property :id, Serial
# ...
has n, :raid_participants, :class_name => 'War::RaidParticipants'
#FIXME: see hack below
#FIXME: HACK alert
# this is a workaround for broken m:n associations
def characters
@characters || @characters = raid_participants.character
end
def remove_characters(cs)
unless cs.empty?
raid_participants.all(:character_id => cs.collect {|c| c.id}).destroy!
end
@characters = raid_participants.character
end
before :save do
characters unless @characters
cs = raid_participants.character
cs.each do |c|
c.destroy unless c.in? @characters
end
@characters.each do |c|
raid_participants.new(:character_id => c.id) unless c.in? cs
end
end
before :destroy do
raid_participants.destroy!
end
end
class RaidParticipants
include DataMapper::Resource
property :raid_id, Integer, :key => true
property :character_id, Integer, :key => true
belongs_to :raid, :class_name => 'War::Raid', :child_key => [:raid_id]
belongs_to :character, :class_name => 'War::Character', :child_key => [:character_id]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment