This repository has been archived by the owner on Feb 13, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
denormalization_with_arrays.rb
96 lines (79 loc) · 1.69 KB
/
denormalization_with_arrays.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
require_relative "activerecord_setup"
ActiveRecord::Schema.define do
create_table :foos, force: true do |t|
t.jsonb :bar_links
t.timestamps
end
create_table :bars, force: true do |t|
t.timestamps
end
end
module DenormalizedAssociations
def denormalized_has_many(associated_table_name)
define_method associated_table_name do
associated_table_name.
to_s.
classify.
constantize.
where(
id: send("#{associated_table_name.to_s.singularize}_links").map do |link|
link["id"]
end
)
end
define_method "#{associated_table_name.to_s.singularize}_ids" do
send("#{associated_table_name.to_s.singularize}_links").map do |link|
link["id"]
end
end
end
end
class ActiveRecord::Base
extend DenormalizedAssociations
end
class Foo < ActiveRecord::Base
denormalized_has_many :bars
end
class Bar < ActiveRecord::Base
end
class DenormalizationTest < Minitest::Test
def setup
Foo.destroy_all
Bar.destroy_all
end
def test_has_many
5.times do
Bar.create
end
foo = Foo.create(
bar_links: [
{ id: 1, fruit: "banana" },
{ id: 2, fruit: "orange" }
]
)
assert_equal(foo.bars.map(&:id), [1, 2])
assert_equal(foo.bar_ids, [1, 2])
end
def test_querying
5.times do
Bar.create
end
foo = Foo.create(
bar_links: [
{ id: 1, fruit: "banana" },
{ id: 2, fruit: "orange" }
]
)
2.times do
Foo.create(
bar_links: [
{ id: 3, fruit: "pear" }
]
)
end
assert_equal(
[ foo ],
Foo.where("bar_links @> '[{\"id\": 1}]'")
)
end
end