I have a simple database with 2 models:
class Fighter < ActiveRecrod::Base
has_many :fights
has_many :opponents, through :fights
end
class Fight < ActiveRecord::Base
belongs_to :fighter
belongs_to :opponent, class_name: 'Fighter'
end`
What should I add for this to work:
a = Fighter.create
b = Fighter.create
a.opponents << b
b.fights <- should return a value`
a.fights
should return newly created Fight
b.fights
should return newly created Fight as well
so far only a.fights
returns the value
I came up with such idea:
class Fight < ActiveRecord::Base
belongs_to :fighter
belongs_to :opponent, class_name: 'Fighter'
after_create :create_association
def create_association
Fighter.find(opponent_id).fights << self
end
end
but calling another model from Fight doesn't seem right.
I also tried to overload has_man :fights
in Fighter
so that it takes lambda
has_many :fights, -> { where("fighter_id = ? OR opponent_id = ?", self.id, self.id)
but I constantly get error - wrong number of arguments (0 for 2)
after researching a bit, I know I should use a bidirectional self-referential association, similar to this: Bidirectional self referential associations
but when follow this, then I receive two records of a fight in table Fight
. One that is associated with one fighter and another that is associated with second fighter.
I would appreciate help or some hints in how to solve this issue