-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
relatable.rb
51 lines (40 loc) · 1.13 KB
/
relatable.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
module SDG::Relatable
extend ActiveSupport::Concern
included do
has_many :sdg_relations, as: :relatable, dependent: :destroy, class_name: "SDG::Relation"
%w[SDG::Goal SDG::Target SDG::LocalTarget].each do |sdg_type|
has_many sdg_type.constantize.table_name.to_sym,
through: :sdg_relations,
source: :related_sdg,
source_type: sdg_type
end
end
class_methods do
def by_goal(code)
by_sdg_related(SDG::Goal, code)
end
def by_target(code)
by_sdg_related(SDG::Target, code)
end
def by_sdg_related(sdg_class, code)
return all if code.blank?
joins(sdg_class.table_name.to_sym).merge(sdg_class.where(code: code))
end
end
def related_sdgs
sdg_relations.map(&:related_sdg)
end
def sdg_goal_list
sdg_goals.map(&:code).join(", ")
end
def sdg_target_list
sdg_targets.map(&:code).join(", ")
end
def sdg_target_list=(codes)
targets = codes.tr(" ", "").split(",").map { |code| SDG::Target[code] }
transaction do
self.sdg_targets = targets
self.sdg_goals = targets.map(&:goal).uniq
end
end
end