-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathslides_rails_db.html
More file actions
680 lines (640 loc) · 42.8 KB
/
slides_rails_db.html
File metadata and controls
680 lines (640 loc) · 42.8 KB
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Slides for
Rails: Database and Migrations — Ruby on Rails Guides
</title>
<link rel="stylesheet" type="text/css" href="stylesheets/style.css" data-turbo-track="reload">
<link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print">
<link rel="stylesheet" type="text/css" href="stylesheets/highlight.css" data-turbo-track="reload">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="stylesheets/reset.css">
<link rel="stylesheet" href="stylesheets/reveal.css">
<link rel="stylesheet" href="stylesheets/myslide.css" id="theme">
<link rel="stylesheet" href="stylesheets/code.css">
<script src="javascripts/clipboard.js" data-turbo-track="reload"></script>
<script src="javascripts/slides.js" data-turbo-track="reload"></script>
</head>
<body>
<div class="reveal">
<!-- Any section element inside of this container is displayed as a slide -->
<div class="slides">
<section>
<h1>Rails: Database and Migrations</h1><p>Behind Models in Rails there is a database.</p><p>After working through this guide you should</p>
<ul>
<li>Understand what Database Migrations are</li>
<li>Understand how Models relate to Database rows</li>
</ul>
<p><small>Slides - use arrow keys to navigate, esc to return to page view, f for fullscreen</small></p>
</section>
<section><a class='slide_break' href='rails_db.html#slide-0'>▻</a>
<h2 id="models-and-databases"><a class="anchorlink" href="#models-and-databases"><span>1</span> Models and Databases</a></h2><p>In an object-oriented programming language like Ruby we represent
things in the real world with objects in our program. For example if you are
building an application for project management, you might
have objects of classes <code>Project</code> and <code>WorkPackage</code> and <code>User</code>.
These classes also implement the "Business Logic": all the methods
needed for handling projects are actually implemented in the Project class.</p><p>To save these objects permanently (often called "persistance")
we use a relational database,
in most cases Postgres or MySQL/MariaDB. Only the data is stored in the database,
not the behaviour (the "Business Logic" mentioned above).</p><p>Here we hit on an old problem in computer science: storing
objects into a relational database does not work all that well.
This problem is called the
<a href="https://en.wikipedia.org/wiki/Object-relational_impedance_mismatch">Object-relational impedance mismatch</a>
and has been discussed since the early 1980s.</p></section>
<section><a class='slide_break' href='rails_db.html#slide-1'>▻</a>
<h3 id="orms"><a class="anchorlink" href="#orms"><span>1.1</span> ORMs</a></h3><p>Today there exist several Design Patterns and Libraries for solving this.
The solution is called an Object Relational Mapper or ORM.</p><p>Two Patterns used in Rails for this problem are ActiveRecord and ObjectMapper, both
described by Fowler in his 2003 book <a href="https://martinfowler.com/books/eaa.html">Patterns of Enterprise Application Architecture</a>.
ActiveRecord is the default solution used in Rails, we will look into it in detail here.</p><p>Maybe you have used ORMs in other Languages? Some examples are:</p>
<ul>
<li>PHP: <a href="https://www.doctrine-project.org/">Doctrine</a> and <a href="https://propelorm.org/">Propel</a></li>
<li>Java: <a href="https://hibernate.org/">Hibernate</a></li>
<li>Python: <a href="https://www.sqlalchemy.org/">SQL Alchemy</a> and <a href="https://www.fullstackpython.com/object-relational-mappers-orms.html">many more</a></li>
<li>JavaScript+Typescript: <a href="https://sequelize.org/">Sequelize</a>, <a href="https://typeorm.io/">TypeORM</a>, <a href="https://www.prisma.io/">prisma</a> and <a href="https://blog.logrocket.com/best-typescript-orms/#picking-best-typescript-orms">many more</a></li>
</ul>
</section>
<section><a class='slide_break' href='rails_db.html#slide-2'>▻</a>
<h3 id="the-mapping"><a class="anchorlink" href="#the-mapping"><span>1.2</span> The Mapping</a></h3><p>A quick overview of how Objects and Database relate when using
ActiveRecord in Rails:</p><div class="interstitial code">
<pre><code class="highlight plaintext">Database Ruby on Rails
--------------------------- --------------------------
table courses class Course
in the Database in file app/models/course.rb
one row in the table one object of the class Course
an attibute in the table a property of the object
SELECT * FROM courses WHERE id=7 Course.find(7)
</code></pre>
<button class="clipboard-button" data-clipboard-text="Database Ruby on Rails
--------------------------- --------------------------
table courses class Course
in the Database in file app/models/course.rb
one row in the table one object of the class Course
an attibute in the table a property of the object
SELECT * FROM courses WHERE id=7 Course.find(7)
">Copy</button>
</div>
</section>
<section><a class='slide_break' href='rails_db.html#slide-3'>▻</a>
<h3 id="conventions"><a class="anchorlink" href="#conventions"><span>1.3</span> Conventions</a></h3><p>Rails has several conventions regarding ActiveRecord and the database:</p>
<ul>
<li>The model class is written in "pascal case", and uses a singular noun: <code>Course</code> or <code>WorkPackage</code></li>
<li>The table in the database is written in "snake case", and uses the plural of this noun: <code>courses</code> or <code>work_packages</code></li>
<li>The table contains an integer attribute <code>id</code> as its primary key</li>
<li>All the attributes from the database table will show up as properties of the model in Rails automatically</li>
<li>Two extra properties are added: <code>created_at</code> and <code>updated_at</code>.</li>
</ul>
</section>
<section><a class='slide_break' href='rails_db.html#slide-4'>▻</a>
<p>If there's an 1:n relationship between two models, the table on the "one" side will contain a foreign key like so:</p>
<ul>
<li>table <code>users</code> and table <code>phones</code> (one user has many phones)</li>
<li>table <code>phones</code> contains <code>user_id</code> that references <code>users.id</code></li>
</ul>
<p>If there's a n:m relationship between two models, there will be a join table like so:</p>
<ul>
<li>table <code>users</code> and table <code>projects</code> (one user has many projects, one project has many users)</li>
<li>table <code>projects_users</code> contains <code>user_id</code> and <code>project_id</code> (and nothing else)</li>
<li>there is no class in Rails to represent the join table</li>
</ul>
</section>
<section><a class='slide_break' href='rails_db.html#slide-5'>▻</a>
<h3 id="not-following-conventions"><a class="anchorlink" href="#not-following-conventions"><span>1.4</span> Not following Conventions</a></h3><p>If you stick to these conventions, building the web app will be very easy.</p><p>You can deviate from these conventions, but this takes some extra configuration and programming work.</p><p>Here is one scenario where deviating from the conventions might make sense:
You are building a Rails app to replace an old php app, but you want to
keep using the same database. You can start with the models
in Rails configured to fit with your old database, and then refactor and migrate towards
the Rails conventions step by step.</p></section>
<section><a class='slide_break' href='rails_db.html#slide-6'>▻</a>
<h3 id="a-word-on-generators"><a class="anchorlink" href="#a-word-on-generators"><span>1.5</span> A word on generators</a></h3><p>Rails comes with several commands for the command line.</p><div class="interstitial code">
<pre><code class="highlight shell"><span class="nv">$ </span><span class="nb">rails</span> <span class="nt">--help</span>
The most common <span class="nb">rails </span>commands are:
generate Generate new code <span class="o">(</span>short-cut <span class="nb">alias</span>: <span class="s2">"g"</span><span class="o">)</span>
console Start the Rails console <span class="o">(</span>short-cut <span class="nb">alias</span>: <span class="s2">"c"</span><span class="o">)</span>
server Start the Rails server <span class="o">(</span>short-cut <span class="nb">alias</span>: <span class="s2">"s"</span><span class="o">)</span>
<span class="nb">test </span>Run tests except system tests <span class="o">(</span>short-cut <span class="nb">alias</span>: <span class="s2">"t"</span><span class="o">)</span>
<span class="nb">test</span>:system Run system tests
dbconsole Start a console <span class="k">for </span>the database specified <span class="k">in </span>config/database.yml
<span class="o">(</span>short-cut <span class="nb">alias</span>: <span class="s2">"db"</span><span class="o">)</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="$ rails --help
The most common rails commands are:
generate Generate new code (short-cut alias: "g")
console Start the Rails console (short-cut alias: "c")
server Start the Rails server (short-cut alias: "s")
test Run tests except system tests (short-cut alias: "t")
test:system Run system tests
dbconsole Start a console for the database specified in config/database.yml
(short-cut alias: "db")
">Copy</button>
</div>
<p>First we will
use a generator that will help us generate some code.</p></section>
<section><a class='slide_break' href='rails_db.html#slide-7'>▻</a>
<h3 id="how-to-build-a-first-table-generate"><a class="anchorlink" href="#how-to-build-a-first-table-generate"><span>1.6</span> How to build a first Table - generate</a></h3><p>To build the first model and its corresponding database table, use the model generator:</p><div class="interstitial code">
<pre><code class="highlight shell"><span class="nb">rails </span>generate model tweet status zombie
</code></pre>
<button class="clipboard-button" data-clipboard-text="rails generate model tweet status zombie
">Copy</button>
</div>
<p>This will generate a Model <code>Tweet</code> and a migration to create table <code>tweets</code>.
We have not specified any datatypes, therefore status and zombie will
have the default type: string.</p><p>Look at the model generated in file <code>app/models/tweet.rb</code>. It is empty for now.
We do not need to specify properties or their datatypes here, they will be
derived from the database automatically.</p><p>If you ever mistype your <code>rails generate ...</code> line, you can undo it by running <code>rails destroy ...</code>. This will
delete all the files generated.</p></section>
<section><a class='slide_break' href='rails_db.html#slide-8'>▻</a>
<h3 id="how-to-build-a-first-table-edit-migration"><a class="anchorlink" href="#how-to-build-a-first-table-edit-migration"><span>1.7</span> How to build a first Table - edit migration</a></h3><p>Have a look at the migration that was generated in <code>db/migrate/*create_tweets.rb</code>.</p><div class="interstitial code">
<pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">CreateTweets</span> <span class="o"><</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Migration</span><span class="p">[</span><span class="mf">7.0</span><span class="p">]</span>
<span class="k">def</span> <span class="nf">change</span>
<span class="n">create_table</span> <span class="ss">:tweets</span> <span class="k">do</span> <span class="o">|</span><span class="n">t</span><span class="o">|</span>
<span class="n">t</span><span class="p">.</span><span class="nf">string</span> <span class="ss">:status</span>
<span class="n">t</span><span class="p">.</span><span class="nf">string</span> <span class="ss">:zombie</span>
<span class="n">t</span><span class="p">.</span><span class="nf">timestamps</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="class CreateTweets < ActiveRecord::Migration[7.0]
def change
create_table :tweets do |t|
t.string :status
t.string :zombie
t.timestamps
end
end
end
">Copy</button>
</div>
<p>You can edit this migration now.</p></section>
<section><a class='slide_break' href='rails_db.html#slide-9'>▻</a>
<p>For example you could add some more
columns, with other datatypes:</p><div class="interstitial code">
<pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">CreateTweets</span> <span class="o"><</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Migration</span><span class="p">[</span><span class="mf">7.0</span><span class="p">]</span>
<span class="k">def</span> <span class="nf">change</span>
<span class="n">create_table</span> <span class="ss">:tweets</span> <span class="k">do</span> <span class="o">|</span><span class="n">t</span><span class="o">|</span>
<span class="n">t</span><span class="p">.</span><span class="nf">string</span> <span class="ss">:status</span>
<span class="n">t</span><span class="p">.</span><span class="nf">string</span> <span class="ss">:zombie</span>
<span class="n">t</span><span class="p">.</span><span class="nf">integer</span> <span class="ss">:number_of_likes</span>
<span class="n">t</span><span class="p">.</span><span class="nf">boolean</span> <span class="ss">:private</span>
<span class="n">t</span><span class="p">.</span><span class="nf">timestamps</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="class CreateTweets < ActiveRecord::Migration[7.0]
def change
create_table :tweets do |t|
t.string :status
t.string :zombie
t.integer :number_of_likes
t.boolean :private
t.timestamps
end
end
end
">Copy</button>
</div>
<p>We could have specified those extra columns when generating the model like so:</p><div class="interstitial code">
<pre><code class="highlight shell"><span class="nb">rails </span>generate model tweet status zombie number_of_likes:integer private:boolean
</code></pre>
<button class="clipboard-button" data-clipboard-text="rails generate model tweet status zombie number_of_likes:integer private:boolean
">Copy</button>
</div>
</section>
<section><a class='slide_break' href='rails_db.html#slide-10'>▻</a>
<h3 id="how-to-build-a-first-table-run-migration"><a class="anchorlink" href="#how-to-build-a-first-table-run-migration"><span>1.8</span> How to build a first Table - run migration</a></h3><p>Run the migration on the command line with <code>rails db:migrate</code>. This will run the appropriate <code>CREATE TABLE</code> statement in your database.</p><p>After that, the current schema of the database will be saved to
a file <code>db/schema.rb</code>. You never need to edit this file directly.</p></section>
<section><a class='slide_break' href='rails_db.html#slide-11'>▻</a>
<h2 id="database-migrations"><a class="anchorlink" href="#database-migrations"><span>2</span> Database Migrations</a></h2><p>You just saw how you can build a database table and a model
file using <code>generate model</code>. But why is the database table not
created directly? Why generate a migration-file, and then run another command
to apply the migration-file to the database?</p><p>To answer this question we must look at the whole lifespan of
a web project.</p><p>During months and years of development the database schema will change just as much as
the code will change. And both changes belong together: if I push out
a code change to my fellow developers without the database changes,
they will not be able to use the code.</p><p>Database Migrations are a way to communicate database changes.</p></section>
<section><a class='slide_break' href='rails_db.html#slide-12'>▻</a>
<h3 id="one-migration"><a class="anchorlink" href="#one-migration"><span>2.1</span> One Migration</a></h3><p>A "Migration" is a (small) change in the database schema. The change is
described in Ruby and saved to a file in the folder <code>db/migrations</code>.
The files are identified by a timestamp and a unique name, for example:</p><div class="interstitial code">
<pre><code class="highlight plaintext">20231021100433_create_venues.rb
20231021100442_create_events.rb
20231021100501_add_video_link_to_events.rb
</code></pre>
<button class="clipboard-button" data-clipboard-text="20231021100433_create_venues.rb
20231021100442_create_events.rb
20231021100501_add_video_link_to_events.rb
">Copy</button>
</div>
<p>The first two of these migrations were generated by the model generator,
the last one by <code>rails generate migration AddVideoLinkToEvent</code>.</p></section>
<section><a class='slide_break' href='rails_db.html#slide-13'>▻</a>
<h3 id="a-first-example"><a class="anchorlink" href="#a-first-example"><span>2.2</span> A First Example</a></h3><p>Here you see a first example of a migration file. It was created
by the model generator. When it is run, it creates a table from scratch.
The name of the table, and the names and data types of all the columns
are specified:</p><div class="interstitial code">
<pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">CreateEvents</span> <span class="o"><</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Migration</span>
<span class="k">def</span> <span class="nf">change</span>
<span class="n">create_table</span> <span class="ss">:events</span> <span class="k">do</span> <span class="o">|</span><span class="n">t</span><span class="o">|</span>
<span class="n">t</span><span class="p">.</span><span class="nf">string</span> <span class="ss">:title</span>
<span class="n">t</span><span class="p">.</span><span class="nf">text</span> <span class="ss">:description</span>
<span class="n">t</span><span class="p">.</span><span class="nf">datetime</span> <span class="ss">:start_time</span>
<span class="n">t</span><span class="p">.</span><span class="nf">datetime</span> <span class="ss">:stop_time</span>
<span class="n">t</span><span class="p">.</span><span class="nf">boolean</span> <span class="ss">:free</span>
<span class="n">t</span><span class="p">.</span><span class="nf">timestamps</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="class CreateEvents < ActiveRecord::Migration
def change
create_table :events do |t|
t.string :title
t.text :description
t.datetime :start_time
t.datetime :stop_time
t.boolean :free
t.timestamps
end
end
end
">Copy</button>
</div>
<p>Use <code>rails db:migrate</code> on the commandline to apply this migration to the existing database.</p></section>
<section><a class='slide_break' href='rails_db.html#slide-14'>▻</a>
<h3 id="rollback"><a class="anchorlink" href="#rollback"><span>2.3</span> Rollback</a></h3><p>You can think of the migration as a small step forward in changing the
database. If you want, you can also go backward with <code>rails db:rollback</code>.
this will undo the last migration.</p><p>(Not always. If you deleted a table with all it's data, then the rollback
will not bring the data back.)</p><p>During development on your local machine, you can try to formulate
the right migration, apply it, check if it wored, roll it back, change the
migration, apply it again... until you are happy with it.</p><p>But beware: once you have committed and pushed the migration, there is
no going back any more: as soon as other developers have started using
your migration, you cannot roll it back anymore. You can only add more
migration files, with newer timestamps.</p></section>
<section><a class='slide_break' href='rails_db.html#slide-15'>▻</a>
<h3 id="a-real-world-example"><a class="anchorlink" href="#a-real-world-example"><span>2.4</span> a real world example:</a></h3><p>The following output is from upgrading GitLab. GitLab
is written in Rails. Here we can see three migrations being applied to
the existing database.</p><div class="interstitial code">
<pre><code class="highlight plaintext">== 20191120084627 AddEncryptedFieldsToApplicationSettings: migrating ==========
-- add_column(:application_settings, "encrypted_akismet_api_key", :text)
-> 0.0013s
-- add_column(:application_settings, "encrypted_akismet_api_key_iv", :string, {:limit=>255})
-> 0.0007s
-- add_column(:application_settings, "encrypted_elasticsearch_aws_secret_access_key", :text)
-> 0.0007s
-- add_column(:application_settings, "encrypted_elasticsearch_aws_secret_access_key_iv", :string, {:limit=>255})
-> 0.0008s
-- add_column(:application_settings, "encrypted_recaptcha_private_key", :text)
-> 0.0008s
-- add_column(:application_settings, "encrypted_recaptcha_private_key_iv", :string, {:limit=>255})
-> 0.0007s
-- add_column(:application_settings, "encrypted_recaptcha_site_key", :text)
-> 0.0007s
-- add_column(:application_settings, "encrypted_recaptcha_site_key_iv", :string, {:limit=>255})
-> 0.0007s
-- add_column(:application_settings, "encrypted_slack_app_secret", :text)
-> 0.0007s
-- add_column(:application_settings, "encrypted_slack_app_secret_iv", :string, {:limit=>255})
-> 0.0007s
-- add_column(:application_settings, "encrypted_slack_app_verification_token", :text)
-> 0.0007s
-- add_column(:application_settings, "encrypted_slack_app_verification_token_iv", :string, {:limit=>255})
-> 0.0007s
== 20191120084627 AddEncryptedFieldsToApplicationSettings: migrated (0.0095s) =
== 20191120115530 EncryptPlaintextAttributesOnApplicationSettings: migrating ==
== 20191120115530 EncryptPlaintextAttributesOnApplicationSettings: migrated (0.4133s)
== 20191122135327 RemovePlaintextColumnsFromApplicationSettings: migrating ====
-- remove_column(:application_settings, "akismet_api_key")
-> 0.0010s
-- remove_column(:application_settings, "elasticsearch_aws_secret_access_key")
-> 0.0006s
-- remove_column(:application_settings, "recaptcha_private_key")
-> 0.0006s
-- remove_column(:application_settings, "recaptcha_site_key")
-> 0.0006s
-- remove_column(:application_settings, "slack_app_secret")
-> 0.0006s
-- remove_column(:application_settings, "slack_app_verification_token")
-> 0.0007s
== 20191122135327 RemovePlaintextColumnsFromApplicationSettings: migrated (0.0045s)
</code></pre>
<button class="clipboard-button" data-clipboard-text="== 20191120084627 AddEncryptedFieldsToApplicationSettings: migrating ==========
-- add_column(:application_settings, "encrypted_akismet_api_key", :text)
-> 0.0013s
-- add_column(:application_settings, "encrypted_akismet_api_key_iv", :string, {:limit=>255})
-> 0.0007s
-- add_column(:application_settings, "encrypted_elasticsearch_aws_secret_access_key", :text)
-> 0.0007s
-- add_column(:application_settings, "encrypted_elasticsearch_aws_secret_access_key_iv", :string, {:limit=>255})
-> 0.0008s
-- add_column(:application_settings, "encrypted_recaptcha_private_key", :text)
-> 0.0008s
-- add_column(:application_settings, "encrypted_recaptcha_private_key_iv", :string, {:limit=>255})
-> 0.0007s
-- add_column(:application_settings, "encrypted_recaptcha_site_key", :text)
-> 0.0007s
-- add_column(:application_settings, "encrypted_recaptcha_site_key_iv", :string, {:limit=>255})
-> 0.0007s
-- add_column(:application_settings, "encrypted_slack_app_secret", :text)
-> 0.0007s
-- add_column(:application_settings, "encrypted_slack_app_secret_iv", :string, {:limit=>255})
-> 0.0007s
-- add_column(:application_settings, "encrypted_slack_app_verification_token", :text)
-> 0.0007s
-- add_column(:application_settings, "encrypted_slack_app_verification_token_iv", :string, {:limit=>255})
-> 0.0007s
== 20191120084627 AddEncryptedFieldsToApplicationSettings: migrated (0.0095s) =
== 20191120115530 EncryptPlaintextAttributesOnApplicationSettings: migrating ==
== 20191120115530 EncryptPlaintextAttributesOnApplicationSettings: migrated (0.4133s)
== 20191122135327 RemovePlaintextColumnsFromApplicationSettings: migrating ====
-- remove_column(:application_settings, "akismet_api_key")
-> 0.0010s
-- remove_column(:application_settings, "elasticsearch_aws_secret_access_key")
-> 0.0006s
-- remove_column(:application_settings, "recaptcha_private_key")
-> 0.0006s
-- remove_column(:application_settings, "recaptcha_site_key")
-> 0.0006s
-- remove_column(:application_settings, "slack_app_secret")
-> 0.0006s
-- remove_column(:application_settings, "slack_app_verification_token")
-> 0.0007s
== 20191122135327 RemovePlaintextColumnsFromApplicationSettings: migrated (0.0045s)
">Copy</button>
</div>
</section>
<section><a class='slide_break' href='rails_db.html#slide-16'>▻</a>
<h2 id="data-types"><a class="anchorlink" href="#data-types"><span>3</span> Data Types</a></h2><p>You can specify the data type when running the generator.
<code>string</code> is the default Datatype, so these two lines give the same result:</p><div class="interstitial code">
<pre><code class="highlight shell"><span class="nb">rails </span>generate model tweet status zombie likes:integer
<span class="nb">rails </span>generate model tweet:string status:status zombie:status likes:integer
</code></pre>
<button class="clipboard-button" data-clipboard-text="rails generate model tweet status zombie likes:integer
rails generate model tweet:string status:status zombie:status likes:integer
">Copy</button>
</div>
<p>Here are the most important ones to begin:</p>
<ul>
<li><code>:string</code> and <code>:text</code> are synonymous when using postgresql</li>
<li><code>:boolean</code> is for booleans (use this, not a 0 and 1!)</li>
<li><code>:integer</code>, <code>:bigint</code>, <code>:float</code>, <code>:decimal</code>, <code>:numeric</code> are number types</li>
<li><code>:datetime</code>, <code>:time</code>, <code>:date</code>, <code>:daterange</code>, <code>:interval</code> (the last two are postgresql specific)</li>
<li><code>:jsonb</code> is a postgres specific way to store json in an efficient way</li>
<li><code>:enum</code> is postgresql specific</li>
<li><code>:uuid</code> is postgresql specific, can be used for primary keys</li>
<li><code>:inet</code>, <code>:cidr</code>, <code>:macaddr</code> are postgresql specific types for network adresses</li>
<li><code>:binary</code>, <code>:blob</code> for raw binary data</li>
</ul>
</section>
<section><a class='slide_break' href='rails_db.html#slide-17'>▻</a>
<h3 id="details-for-types"><a class="anchorlink" href="#details-for-types"><span>3.1</span> Details for types</a></h3><p>The generator will give you a good first draft of the migration, but sometimes
you will have to edit the migration to add details. For example: say you want to store
a monetary value you would use <code>:decimal</code> as the base datatype:</p><div class="interstitial code">
<pre><code class="highlight shell"><span class="nb">rails </span>generate comic name price_in_euro:decimal
</code></pre>
<button class="clipboard-button" data-clipboard-text="rails generate comic name price_in_euro:decimal
">Copy</button>
</div>
<p>This is the resulting migration:</p><div class="interstitial code">
<pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">CreateComics</span> <span class="o"><</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Migration</span><span class="p">[</span><span class="mf">7.0</span><span class="p">]</span>
<span class="k">def</span> <span class="nf">change</span>
<span class="n">create_table</span> <span class="ss">:comics</span> <span class="k">do</span> <span class="o">|</span><span class="n">t</span><span class="o">|</span>
<span class="n">t</span><span class="p">.</span><span class="nf">string</span> <span class="ss">:name</span>
<span class="n">t</span><span class="p">.</span><span class="nf">decimal</span> <span class="ss">:price_in_euro</span>
<span class="n">t</span><span class="p">.</span><span class="nf">timestamps</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="class CreateComics < ActiveRecord::Migration[7.0]
def change
create_table :comics do |t|
t.string :name
t.decimal :price_in_euro
t.timestamps
end
end
end
">Copy</button>
</div>
<p>To specify that we want 15 digits in all, 2 digits after the comma,
we add <code>:precision</code> and <code>:scale</code></p><div class="interstitial code">
<pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">CreateComics</span> <span class="o"><</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Migration</span><span class="p">[</span><span class="mf">7.0</span><span class="p">]</span>
<span class="k">def</span> <span class="nf">change</span>
<span class="n">create_table</span> <span class="ss">:comics</span> <span class="k">do</span> <span class="o">|</span><span class="n">t</span><span class="o">|</span>
<span class="n">t</span><span class="p">.</span><span class="nf">string</span> <span class="ss">:name</span>
<span class="n">t</span><span class="p">.</span><span class="nf">decimal</span> <span class="ss">:price_in_euro</span><span class="p">,</span> <span class="ss">precision: </span><span class="mi">15</span><span class="p">,</span> <span class="ss">scale: </span><span class="mi">2</span>
<span class="n">t</span><span class="p">.</span><span class="nf">timestamps</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="class CreateComics < ActiveRecord::Migration[7.0]
def change
create_table :comics do |t|
t.string :name
t.decimal :price_in_euro, precision: 15, scale: 2
t.timestamps
end
end
end
">Copy</button>
</div>
<p>Now the price is stored in the database in an optimal way to get
this format, and always retrieved in the right format:</p><div class="interstitial code">
<pre><code class="highlight plaintext"># select * from comics;
id | name | price_in_euro | created_at | updated_at
----+------+---------------+---------------------------+---------------------------
1 | Maus | 100.00 | 2023-10-30 11:45:54.45353 | 2023-10-30 11:45:54.45353
</code></pre>
<button class="clipboard-button" data-clipboard-text="# select * from comics;
id | name | price_in_euro | created_at | updated_at
----+------+---------------+---------------------------+---------------------------
1 | Maus | 100.00 | 2023-10-30 11:45:54.45353 | 2023-10-30 11:45:54.45353
">Copy</button>
</div>
</section>
<section><a class='slide_break' href='rails_db.html#slide-18'>▻</a>
<h3 id="enums"><a class="anchorlink" href="#enums"><span>3.2</span> Enums</a></h3><p>Often we want to store a restricted set of possible values. Size could be small, medium or large,
status could be draft, published and archived, ... and so on.</p><p>There are several ways to store such a value in the database and use it in Rails.</p>
<ol>
<li>Just use a string</li>
<li>Store an Integer in the Database, use <code>enum</code> in the Model to map this integer to a symbol</li>
<li>Create an Enum Type in the Database, use <code>enum</code> in the Model to map this enum to a symbol</li>
<li>Create a separate Table for the possible values, reference the table through a foreign key</li>
</ol>
<p>This next example shows the first three options:</p><div class="interstitial code">
<pre><code class="highlight shell"><span class="nb">rails </span>g model comic name category status:integer format:enum
</code></pre>
<button class="clipboard-button" data-clipboard-text="rails g model comic name category status:integer format:enum
">Copy</button>
</div>
<p>For category (just a string) and status (integer in the database) we do
not need to change the migration. We can add a default value.
For the enum we need to add a definition to the migration, it needs
to be created before it is used:</p><div class="interstitial code">
<pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">CreateComics</span> <span class="o"><</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Migration</span><span class="p">[</span><span class="mf">7.0</span><span class="p">]</span>
<span class="k">def</span> <span class="nf">change</span>
<span class="n">create_enum</span> <span class="ss">:comic_format</span><span class="p">,</span> <span class="p">[</span><span class="s2">"book"</span><span class="p">,</span> <span class="s2">"webcomic"</span><span class="p">,</span> <span class="s2">"motion comic"</span><span class="p">]</span>
<span class="n">create_table</span> <span class="ss">:comics</span> <span class="k">do</span> <span class="o">|</span><span class="n">t</span><span class="o">|</span>
<span class="n">t</span><span class="p">.</span><span class="nf">string</span> <span class="ss">:name</span>
<span class="n">t</span><span class="p">.</span><span class="nf">string</span> <span class="ss">:category</span>
<span class="n">t</span><span class="p">.</span><span class="nf">integer</span> <span class="ss">:status</span><span class="p">,</span> <span class="ss">default: </span><span class="mi">0</span><span class="p">,</span> <span class="ss">null: </span><span class="kp">false</span>
<span class="n">t</span><span class="p">.</span><span class="nf">enum</span> <span class="ss">:format</span><span class="p">,</span> <span class="ss">enum_type: :comic_format</span><span class="p">,</span> <span class="ss">default: </span><span class="s2">"book"</span><span class="p">,</span> <span class="ss">null: </span><span class="kp">false</span>
<span class="n">t</span><span class="p">.</span><span class="nf">timestamps</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="class CreateComics < ActiveRecord::Migration[7.0]
def change
create_enum :comic_format, ["book", "webcomic", "motion comic"]
create_table :comics do |t|
t.string :name
t.string :category
t.integer :status, default: 0, null: false
t.enum :format, enum_type: :comic_format, default: "book", null: false
t.timestamps
end
end
end
">Copy</button>
</div>
<p>In the model file <code>app/model/comic.rb</code> we add the
mapping from the database to rails:</p><div class="interstitial code">
<pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">Comic</span> <span class="o"><</span> <span class="no">ApplicationRecord</span>
<span class="n">enum</span> <span class="ss">status: </span><span class="p">{</span>
<span class="ss">draft: </span><span class="mi">0</span><span class="p">,</span> <span class="ss">published: </span><span class="mi">1</span><span class="p">,</span> <span class="ss">archived: </span><span class="mi">2</span>
<span class="p">},</span> <span class="ss">_prefix: </span><span class="kp">true</span>
<span class="n">enum</span> <span class="ss">format: </span><span class="p">{</span>
<span class="ss">book: </span><span class="s2">"book"</span><span class="p">,</span> <span class="ss">webcomic: </span><span class="s2">"webcomic"</span><span class="p">,</span> <span class="ss">motion_comic: </span><span class="s2">"motion comic"</span>
<span class="p">},</span> <span class="ss">_prefix: </span><span class="kp">true</span>
<span class="k">end</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="class Comic < ApplicationRecord
enum status: {
draft: 0, published: 1, archived: 2
}, _prefix: true
enum format: {
book: "book", webcomic: "webcomic", motion_comic: "motion comic"
}, _prefix: true
end
">Copy</button>
</div>
<p>Now we can work with the enums on the rails console:</p><div class="interstitial code">
<pre><code class="highlight plaintext">railsconsole> c = Comic.new(name: 'Maus', status: :draft, format: :book)
=> #<Comic:0x00000001063d4fa8 id: nil, name: 'Maus', category: nil, status: "draft", format: "book", ...
irb(main):003> c.save
TRANSACTION (0.3ms) BEGIN
Comic Create (3.9ms) INSERT INTO "comics" ("name", "category", "status", "format", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $6) RETURNING "id" [["name", nil], ["category", nil], ["status", 0], ["format", "book"], ...]
TRANSACTION (0.8ms) COMMIT
=> true
</code></pre>
<button class="clipboard-button" data-clipboard-text="railsconsole> c = Comic.new(name: 'Maus', status: :draft, format: :book)
=> #<Comic:0x00000001063d4fa8 id: nil, name: 'Maus', category: nil, status: "draft", format: "book", ...
irb(main):003> c.save
TRANSACTION (0.3ms) BEGIN
Comic Create (3.9ms) INSERT INTO "comics" ("name", "category", "status", "format", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $6) RETURNING "id" [["name", nil], ["category", nil], ["status", 0], ["format", "book"], ...]
TRANSACTION (0.8ms) COMMIT
=> true
">Copy</button>
</div>
<p>Notice how the status is converted to 0.</p><p>Trying to create an invalid status or format will raise a runtime error:</p><div class="interstitial code">
<pre><code class="highlight plaintext">railsconsole> c = Comic.new(name: 'broken', status: :daft, format: :nook)
num.rb:157:in `assert_valid_value': 'daft' is not a valid status (ArgumentError)
raise ArgumentError, "'#{value}' is not a valid #{name}"
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
railsconsole> c = Comic.new(name: 'broken', status: :draft, format: :nook)
enum.rb:157:in `assert_valid_value': 'nook' is not a valid format (ArgumentError)
</code></pre>
<button class="clipboard-button" data-clipboard-text="railsconsole> c = Comic.new(name: 'broken', status: :daft, format: :nook)
num.rb:157:in `assert_valid_value': 'daft' is not a valid status (ArgumentError)
raise ArgumentError, "'#{value}' is not a valid #{name}"
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
railsconsole> c = Comic.new(name: 'broken', status: :draft, format: :nook)
enum.rb:157:in `assert_valid_value': 'nook' is not a valid format (ArgumentError)
">Copy</button>
</div>
<p>We also get a few convenience methods for working with status and format:</p><div class="interstitial code">
<pre><code class="highlight plaintext">railsconsole> c.status_published?
=> false
railsconsole> c.status_published!
TRANSACTION (7.9ms) BEGIN
Comic Update (13.8ms) UPDATE "comics" SET "status" = $1, "updated_at" = $2 WHERE "comics"."id" = $3 [["status", 1], ["updated_at", "2023-10-30 11:20:34.867427"], ["id", 1]]
TRANSACTION (1.1ms) COMMIT
=> true
</code></pre>
<button class="clipboard-button" data-clipboard-text="railsconsole> c.status_published?
=> false
railsconsole> c.status_published!
TRANSACTION (7.9ms) BEGIN
Comic Update (13.8ms) UPDATE "comics" SET "status" = $1, "updated_at" = $2 WHERE "comics"."id" = $3 [["status", 1], ["updated_at", "2023-10-30 11:20:34.867427"], ["id", 1]]
TRANSACTION (1.1ms) COMMIT
=> true
">Copy</button>
</div>
</section>
<section><a class='slide_break' href='rails_db.html#slide-19'>▻</a>
<h2 id="on-documentation"><a class="anchorlink" href="#on-documentation"><span>4</span> On Documentation</a></h2><p>You could have learned all this and more from
the Rails Guides: <a href="https://guides.rubyonrails.org/active_record_basics.html">ActiveRecord Basics</a>, <a href="https://guides.rubyonrails.org/active_record_querying.html">Active Record Query Interface</a> and .
Set a bookmark for the guides now! Use them as a reference from now on!</p><p>If you are offline now and again you should have the Ruby and Rails documentation available
locally on your computer. A handy tool for this on mac os x is
<a href="https://kapeli.com/dash">Dash</a>. This is what a Rails Guide looks like in Dash:</p><p><img src="images/dash-rails-guide.png" alt="Dash"></p></section>
<section><a class='slide_break' href='rails_db.html#slide-20'>▻</a>
<h3 id="further-reading"><a class="anchorlink" href="#further-reading"><span>4.1</span> Further reading</a></h3>
<ul>
<li>The Rails Guides give a good introduction to a subject area:
<ul>
<li>Rails Guide: <a href="https://guides.rubyonrails.org/active_record_migrations.html">Active Record Migrations</a></li>
</ul></li>
<li>Use the <a href="https://edgeapi.rubyonrails.org/">Rails API</a> documentation to look up the details:
<ul>
<li><a href="https://edgeapi.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_column">add_column</a> lists all the possible data types for columns</li>
<li><a href="https://guides.rubyonrails.org/active_record_postgresql.html">Rails Guide for Postgresql</a> for postgres specific types like daterange, uuid or jsonb</li>
</ul></li>
</ul>
</div></section>
</div>
</div>
<!-- End slides. -->
<!-- Required JS files. -->
<script src="javascripts/reveal.js"></script>
<script src="javascripts/search.js"></script>
<script src="javascripts/markdown.js"></script>
<script>
// Also available as an ES module, see:
// https://revealjs.com/initialization/
Reveal.initialize({
controls: false,
progress: true,
center: false,
hash: true,
// The "normal" size of the presentation, aspect ratio will
// be preserved when the presentation is scaled to fit different
// resolutions. Can be specified using percentage units.
width: 1000,
height: 600,
disableLayout: false,
// Factor of the display size that should remain empty around
// the content
margin: 0.05,
// Bounds for smallest/largest possible scale to apply to content
minScale: 0.2,
maxScale: 10.0,
keyboard: {
27: () => {
// do something custom when ESC is pressed
var new_url = window.location.pathname.replace('slides_', '') + window.location.hash.replace('/','slide-');
window.location = new_url;
},
191: 'toggleHelp',
13: 'next', // go to the next slide when the ENTER key is pressed
},
// Learn about plugins: https://revealjs.com/plugins/
plugins: [ RevealSearch, RevealMarkdown ]
});
</script>
</body>
</html>