-
-
Notifications
You must be signed in to change notification settings - Fork 531
/
Copy pathvendor.rb
63 lines (52 loc) · 1.39 KB
/
vendor.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# == Schema Information
#
# Table name: vendors
#
# id :bigint not null, primary key
# active :boolean default(TRUE)
# address :string
# business_name :string
# comment :string
# contact_name :string
# email :string
# latitude :float
# longitude :float
# phone :string
# created_at :datetime not null
# updated_at :datetime not null
# organization_id :integer
#
class Vendor < ApplicationRecord
has_paper_trail
include Provideable
include Geocodable
include Filterable
has_many :purchases, inverse_of: :vendor, dependent: :destroy
validates :business_name, presence: true
scope :alphabetized, -> { order(:business_name) }
scope :active, -> { where(active: true) }
scope :with_volumes, -> {
left_joins(purchases: :line_items)
.select("vendors.*, SUM(COALESCE(line_items.quantity, 0)) AS volume")
.group(:id)
}
before_destroy :check_for_purchases, prepend: true
def volume
LineItem.where(
itemizable_type: "Purchase",
itemizable_id: purchase_ids
).sum(:quantity)
end
def deactivate!
update!(active: false)
end
def reactivate!
update!(active: true)
end
private
def check_for_purchases
return if purchases.empty?
errors.add(:base, "Vendor has purchase items")
throw(:abort)
end
end