From 767a43bb0f6e9552bf587e165cfd968fc6a512b7 Mon Sep 17 00:00:00 2001 From: rgarcia Date: Wed, 3 May 2017 18:43:22 +0200 Subject: [PATCH] Adds DB constraint to avoid duplicate balloted investments --- ...3163330_add_uniq_index_for_ballot_lines.rb | 5 ++++ db/schema.rb | 3 ++- spec/models/budget/ballot_spec.rb | 23 +++++++++++++++++++ 3 files changed, 30 insertions(+), 1 deletion(-) create mode 100644 db/migrate/20170503163330_add_uniq_index_for_ballot_lines.rb diff --git a/db/migrate/20170503163330_add_uniq_index_for_ballot_lines.rb b/db/migrate/20170503163330_add_uniq_index_for_ballot_lines.rb new file mode 100644 index 000000000..dec90f329 --- /dev/null +++ b/db/migrate/20170503163330_add_uniq_index_for_ballot_lines.rb @@ -0,0 +1,5 @@ +class AddUniqIndexForBallotLines < ActiveRecord::Migration + def change + add_index :budget_ballot_lines, [:ballot_id, :investment_id], unique: true + end +end diff --git a/db/schema.rb b/db/schema.rb index 4dc2fb2c4..a56818609 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -11,7 +11,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema.define(version: 20170428111355) do +ActiveRecord::Schema.define(version: 20170503163330) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" @@ -88,6 +88,7 @@ ActiveRecord::Schema.define(version: 20170428111355) do t.integer "heading_id" end + add_index "budget_ballot_lines", ["ballot_id", "investment_id"], name: "index_budget_ballot_lines_on_ballot_id_and_investment_id", unique: true, using: :btree add_index "budget_ballot_lines", ["ballot_id"], name: "index_budget_ballot_lines_on_ballot_id", using: :btree add_index "budget_ballot_lines", ["investment_id"], name: "index_budget_ballot_lines_on_investment_id", using: :btree diff --git a/spec/models/budget/ballot_spec.rb b/spec/models/budget/ballot_spec.rb index 3a9f9f232..e0eca4c38 100644 --- a/spec/models/budget/ballot_spec.rb +++ b/spec/models/budget/ballot_spec.rb @@ -2,6 +2,29 @@ require 'rails_helper' describe Budget::Ballot do + describe "validations" do + + it "should be valid" do + budget = create(:budget) + ballot = create(:budget_ballot, budget: budget) + + expect(ballot).to be_valid + end + + it "should not be valid with the same investment twice" do + budget = create(:budget) + group = create(:budget_group, budget: budget) + heading = create(:budget_heading, group: group) + investment = create(:budget_investment, :selected, heading: heading) + + ballot = create(:budget_ballot, budget: budget) + ballot.investments << investment + + expect { ballot.investments << investment }.to raise_error(ActiveRecord::RecordNotUnique) + end + + end + describe "#amount_spent" do it "returns the total amount spent in investments" do budget = create(:budget)