-1

So I want to implement many to many relation between these two models:

class Bet < ActiveRecord::Base
  belongs_to :betting_event
  has_and_belongs_to_many :gambler_bets
  validates_presence_of :odd, :outcome, :description, :betting_event_id 

end

And

class GamblerBet < ActiveRecord::Base
  belongs_to :gambler
  has_and_belongs_to_many :bets

end

I wrote and ran a migration :

class CreateBetsGamblerBets < ActiveRecord::Migration
  def change
    create_table :bets_gambler_bets, :id => false do |t|
      t.belongs_to :bet
      t.belongs_to :gambler_bet
    end
  end
end

So the question is: where and how to write a method that would add bets to a Gambler and store every one of them with bet_id and gambler_bet_id in bets_gambler_bet table ?

uvytautas
  • 518
  • 8
  • 18

1 Answers1

0

If you want to implement HABTM, I think you need many to many between Gambler and Bet. You would require the following in Bet model:

#bet.rb
class Bet < ActiveRecord::Base
    has_and_belongs_to_many :gamblers
end

and the following in Gambler model:

#gambler.rb
class Gambler < ActiveRecord::Base
    has_and_belongs_to_many :bets
end

and this would be your migration with table name bets_gamblers

class CreateBetsGamblers < ActiveRecord::Migration
  def change
    create_table :bets_gamblers, :id => false do |t|
        t.belongs_to :bets
        t.belongs_to :gamblers
    end
  end
end

To query bets of a Gambler with instance of @gambler

@gambler.bets #this would give you all the bets of a gambler

To insert a bet @bet into the bets of a @gambler

@gambler.bets << @bet

You can do a similar thing with your model GamblerBet, but if its only for having a many to many relation between Gambler and Bet, the relation above would work better.

Raman
  • 1,221
  • 13
  • 20
  • you answered my question, but I will stick with my relation because Gambler can have multiple gambler bets that consist of multiple different Bets. `@gambler_bet.bets << @bet` can I surround this code in method in `GamblerBet` model? @Raman – uvytautas Nov 30 '15 at 16:08
  • Yes for sure a method like the following can be added to `GamblerBet`: def add_bet(bet) self.bets << bet end – Raman Nov 30 '15 at 16:18