Skip to content

Commit f7e47d5

Browse files
committed
add model and DB constraint for Movement#amount (can't be equal to 0)
1 parent af36b95 commit f7e47d5

File tree

3 files changed

+13
-1
lines changed

3 files changed

+13
-1
lines changed

app/models/movement.rb

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ class Movement < ActiveRecord::Base
1818
where(created_at: month.beginning_of_month..month.end_of_month)
1919
}
2020

21+
validates :amount, numericality: { other_than: 0 }
22+
2123
after_create do
2224
account.update_balance
2325
end
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
class AddAmountConstraintToMovements < ActiveRecord::Migration
2+
def change
3+
# Destroy movements (and parent transfer) with amount equal to 0
4+
Movement.includes(:transfer).where(amount: 0).find_each do |movement|
5+
movement.transfer&.destroy
6+
end
7+
8+
execute 'ALTER TABLE movements ADD CONSTRAINT non_zero_amount CHECK(amount != 0)'
9+
end
10+
end

db/schema.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
#
1212
# It's strongly recommended that you check this file into your version control system.
1313

14-
ActiveRecord::Schema.define(version: 20180924164456) do
14+
ActiveRecord::Schema.define(version: 20181004200104) do
1515

1616
# These are extensions that must be enabled in order to support this database
1717
enable_extension "plpgsql"

0 commit comments

Comments
 (0)