From d6db150fcd46a0bf607bf5462079f5aabccbb591 Mon Sep 17 00:00:00 2001 From: YarekTenko Date: Thu, 23 Mar 2017 10:37:54 -0700 Subject: [PATCH] Add has_many Debts relationship to Bet This will help easily diplay or manipulate the Debts that are associated with a particular Bet. --- app/models/bet.rb | 4 +++- app/models/debt.rb | 1 + ...has_many_belongs_to_relationship_between_bet_and_debt.rb | 6 ++++++ db/schema.rb | 4 +++- 4 files changed, 13 insertions(+), 2 deletions(-) create mode 100644 db/migrate/20170323164658_add_has_many_belongs_to_relationship_between_bet_and_debt.rb diff --git a/app/models/bet.rb b/app/models/bet.rb index 308d656..8e58e11 100644 --- a/app/models/bet.rb +++ b/app/models/bet.rb @@ -2,6 +2,7 @@ class Bet < ApplicationRecord has_many :users, through: :user_bets has_many :user_bets has_many :options, class_name: 'BetOption' + has_many :debts belongs_to :creator, class_name: 'User' validates :expires_at, presence: true @@ -15,7 +16,8 @@ def resolve(winning_option:) Debt.create( creditor: won_bet.user, debtor: lost_bet.user, - amount: amount_owed(lost_bet, won_bet) + amount: amount_owed(lost_bet, won_bet), + bet: self ) end end diff --git a/app/models/debt.rb b/app/models/debt.rb index 7ae3891..951347c 100644 --- a/app/models/debt.rb +++ b/app/models/debt.rb @@ -1,4 +1,5 @@ class Debt < ApplicationRecord belongs_to :debtor, class_name: 'User' belongs_to :creditor, class_name: 'User' + belongs_to :bet, optional: true end diff --git a/db/migrate/20170323164658_add_has_many_belongs_to_relationship_between_bet_and_debt.rb b/db/migrate/20170323164658_add_has_many_belongs_to_relationship_between_bet_and_debt.rb new file mode 100644 index 0000000..c6ed9b3 --- /dev/null +++ b/db/migrate/20170323164658_add_has_many_belongs_to_relationship_between_bet_and_debt.rb @@ -0,0 +1,6 @@ +class AddHasManyBelongsToRelationshipBetweenBetAndDebt < + ActiveRecord::Migration[5.0] + def change + add_reference :debts, :bet, foreign_key: true + end +end diff --git a/db/schema.rb b/db/schema.rb index 8d0d7ec..e370c5d 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,7 +10,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema.define(version: 20170323160837) do +ActiveRecord::Schema.define(version: 20170323164658) do create_table "bet_options", force: :cascade do |t| t.text "option_text" @@ -37,6 +37,8 @@ t.datetime "created_at", null: false t.datetime "updated_at", null: false t.datetime "payment_date" + t.integer "bet_id" + t.index ["bet_id"], name: "index_debts_on_bet_id" t.index ["creditor_id"], name: "index_debts_on_creditor_id" t.index ["debtor_id"], name: "index_debts_on_debtor_id" end