kronosapiens.github.io - Exploring the ActiveRecord Metaphor









Search Preview

Exploring the ActiveRecord Metaphor

kronosapiens.github.io
We’re wrapping up week 4 at the Flatiron School. One of the big topics of the week was ActiveRecord, an ORM (Object-Relational Mapper) that makes it easy to ...
.io > kronosapiens.github.io

SEO audit: Content analysis

Language Error! No language localisation is found.
Title Exploring the ActiveRecord Metaphor
Text / HTML ratio 71 %
Frame Excellent! The website does not use iFrame solutions.
Flash Excellent! The website does not have any flash contents.
Keywords cloud table ActiveRecord class books Author end find column Book “books” called instances “id” database “genres” < number key “authors”
Keywords consistency
Keyword Content Title Description Headings
table 47
ActiveRecord 29
class 27
books 23
Author 22
end 18
Headings
H1 H2 H3 H4 H5 H6
2 1 0 0 0 0
Images We found 5 images on this web page.

SEO Keywords (Single)

Keyword Occurrence Density
table 47 2.35 %
ActiveRecord 29 1.45 %
class 27 1.35 %
books 23 1.15 %
Author 22 1.10 %
end 18 0.90 %
find 18 0.90 %
column 18 0.90 %
14 0.70 %
Book 14 0.70 %
“books” 13 0.65 %
called 13 0.65 %
instances 12 0.60 %
“id” 12 0.60 %
database 12 0.60 %
“genres” 11 0.55 %
< 11 0.55 %
number 10 0.50 %
key 10 0.50 %
“authors” 9 0.45 %

SEO Keywords (Two Word)

Keyword Occurrence Density
in the 14 0.70 %
of the 13 0.65 %
to the 13 0.65 %
that it 11 0.55 %
“books” table 10 0.50 %
instances of 9 0.45 %
a column 9 0.45 %
and find 8 0.40 %
column called 8 0.40 %
the “books” 8 0.40 %
with the 7 0.35 %
< ActiveRecordBase 7 0.35 %
end end 7 0.35 %
a table 6 0.30 %
“genres” table 6 0.30 %
‘has_many books’ 6 0.30 %
primary key 6 0.30 %
table and 6 0.30 %
the “authors” 6 0.30 %
to go 5 0.25 %

SEO Keywords (Three Word)

Keyword Occurrence Density Possible Spam
the “books” table 8 0.40 % No
a column called 7 0.35 % No
and find the 5 0.25 % No
in the table 4 0.20 % No
on down to 4 0.20 % No
the “authors” table 4 0.20 % No
< ActiveRecordBase has_many 4 0.20 % No
ActiveRecordBase has_many books 4 0.20 % No
to the “books” 4 0.20 % No
the “genres” table 4 0.20 % No
< ActiveRecordMigration def 4 0.20 % No
instances of Author 4 0.20 % No
table and find 4 0.20 % No
the ‘authors’ table 4 0.20 % No
the Author class 4 0.20 % No
ActiveRecordMigration def change 4 0.20 % No
instances of Book 4 0.20 % No
do table tablestring 3 0.15 % No
table tablestring name 3 0.15 % No
end end end 3 0.15 % No

SEO Keywords (Four Word)

Keyword Occurrence Density Possible Spam
to the “books” table 4 0.20 % No
< ActiveRecordMigration def change 4 0.20 % No
< ActiveRecordBase has_many books 4 0.20 % No
ActiveRecordMigration def change create_table 3 0.15 % No
that it ‘has_many books’ 3 0.15 % No
the name of the 3 0.15 % No
class Author < ActiveRecordBase 3 0.15 % No
do table tablestring name 3 0.15 % No
Genre < ActiveRecordBase has_many 2 0.10 % No
Author < ActiveRecordBase has_many 2 0.10 % No
class Genre < ActiveRecordBase 2 0.10 % No
tell the Book class 2 0.10 % No
ActiveRecordBase has_many books has_many 2 0.10 % No
that it ‘belongs_to author’ 2 0.10 % No
through => books end 2 0.10 % No
but forget to tell 2 0.10 % No
in the “authors” table 2 0.10 % No
Book that it ‘belongs_to 2 0.10 % No
ActiveRecordBase has_many books end 2 0.10 % No
Book class that it 2 0.10 % No

Internal links in - kronosapiens.github.io

About
About
Strange Loops and Blockchains
Strange Loops and Blockchains
Trie, Merkle, Patricia: A Blockchain Story
Trie, Merkle, Patricia: A Blockchain Story
Reputation Systems: Promise and Peril
Reputation Systems: Promise and Peril
The Future of Housing, in Three Parts
The Future of Housing, in Three Parts
Proof of Work vs Proof of Stake: a Mirror of History
Proof of Work vs Proof of Stake: a Mirror of History
Introducing Talmud
Introducing Talmud
The Economics of Urban Farming
The Economics of Urban Farming
Time and Authority
Time and Authority
On Meaning in Games
On Meaning in Games
Objective Functions in Machine Learning
Objective Functions in Machine Learning
A Basic Computing Curriculum
A Basic Computing Curriculum
The Problem of Information II
The Problem of Information II
The Problem of Information
The Problem of Information
Elements of Modern Computing
Elements of Modern Computing
Blockchain as Talmud
Blockchain as Talmud
Understanding Variational Inference
Understanding Variational Inference
OpsWorks, Flask, and Chef
OpsWorks, Flask, and Chef
On Learning Some Math
On Learning Some Math
Understanding Unix Permissions
Understanding Unix Permissions
30 Feet from Michael Bloomberg
30 Feet from Michael Bloomberg
The Academy: A Machine Learning Framework
The Academy: A Machine Learning Framework
Setting up a queue service: Django, RabbitMQ, Celery on AWS
Setting up a queue service: Django, RabbitMQ, Celery on AWS
Versioning and Orthogonality in an API
Versioning and Orthogonality in an API
Designing to be Subclassed
Designing to be Subclassed
Understanding Contexts in Flask
Understanding Contexts in Flask
Setting up Unit Tests with Flask, SQLAlchemy, and Postgres
Setting up Unit Tests with Flask, SQLAlchemy, and Postgres
Understanding Package Imports in Python
Understanding Package Imports in Python
Setting up Virtual Environments in Python
Setting up Virtual Environments in Python
Creating superfunctions in Python
Creating superfunctions in Python
Some Recent Adventures
Some Recent Adventures
Sorting in pandas
Sorting in pandas
Mimicking DCI through Integration Tests
Mimicking DCI through Integration Tests
From Ruby to Python
From Ruby to Python
Self-Focus vs. Collaboration in a Programming School
Self-Focus vs. Collaboration in a Programming School
Designing Software to Influence Behavior
Designing Software to Influence Behavior
Maintaining Octopress themes as git submodules
Maintaining Octopress themes as git submodules
Setting up a test suite with FactoryGirl and Faker
Setting up a test suite with FactoryGirl and Faker
To Unit Test or not to Unit Test
To Unit Test or not to Unit Test
A Dynamic and Generally Efficient Front-End Filtering Algorithm
A Dynamic and Generally Efficient Front-End Filtering Algorithm
Trails & Ways: A Look at Rails Routing
Trails & Ways: A Look at Rails Routing
Getting Cozy with rspec_helper
Getting Cozy with rspec_helper
Exploring the ActiveRecord Metaphor
Exploring the ActiveRecord Metaphor
Civic Hacking as Inspiration
Civic Hacking as Inspiration
From Scheme to Ruby
From Scheme to Ruby
Setting up Auto-Indent in Sublime Text 2
Setting up Auto-Indent in Sublime Text 2
hello world
hello world
via RSS
Abacus

Kronosapiens.github.io Spined HTML


Exploring the ActiveRecord Metaphor AbacusWell-nighExploring the ActiveRecord Metaphor Mar 4, 2014 We’re wrapping up week 4 at the Flatiron School. One of the big topics of the week was ActiveRecord, an ORM (Object-Relational Mapper) that makes it easy to set up and interact with databases within your Ruby program. Having spent a number of days working with SQLite3 databases using the low-level “native language” of SQL (Structured Query Language), I and the other students quickly realized how much of a help ActiveRecord would be in towers ramified Ruby applications. ActiveRecord lets you build your database functionality directly into your classes, lamister the ramified syntax of SQL – enabling you to utopian yonder the database layer, and treat your database interactions like any other object method. All is not rainbows and kittens, however. Only well-nigh 90% rainbows and kittens. ActiveRecord achieves its magic by equipping your classes with a DSL (domain-specific language), a special syntax used only for ActiveRecord.Constructiveutilization of ActiveRecord requires constructive utilization of the ActiveRecord DSL – which requires a thorough understanding of the metaphors underlying ActiveRecord. My First ActiveRecord Notes ActiveRecord works by creating links between tables in a database (which we don’t see) and their respective classes (which we do see). For every database table that we want in our application, ActiveRecord requires us to create a respective matriculation which links to it. Every entry in a table (every row) corresponds to an instance of the class, and we interact with the data in the table by sending messages to those instances. Consider an example: Given a table “authors”, we create a respective matriculation “Author”. Every row in the “authors” table would correspond to an instance of Author. By querying that instance, we can edit the information represented by that instance, without overly having to deal with the database directly. Metaphorically, we can think of a database table representing a library, with each row in the table representing a typesetting in that library. Without ActiveRecord, you would have to go into that library and squint up information in the books yourself. With ActiveRecord, however (bear with me), the books come to life. To get information out of the library, just go up to the books and ask them questions. They’ll be surprisingly intelligent. Know what else? THE LIBRARY ITSELF IS ALIVE. You can, like, talk to it. Holy shit. The Pagemaster Moby Games Cool, huh? The lawmaking to build all this looks as follows: In your migration file, ‘01_create_authors.rb’, located in ‘db/migrations/’: matriculation CreateAuthors < ActiveRecord::Migration def transpiration create_table :authors do |table| table.string :name end end end Note: ActiveRecord depends heavily on pursuit convention. In this case, the name of the file (‘01_create_authors’) must correspond to the name of the matriculation (‘CreateAuthors’), by substituting every underscore and lowercase letter for the respective uppercase letter. This is not optional. In your matriculation definition file, ‘author.rb’, located in ‘app/models/’: matriculationTragedian< ActiveRecord::Base end This is really all it takes. ActiveRecord is intelligent unbearable to recognize the connection between the ‘authors’ table and theTragedianmatriculation – this, in fact, is the intelligence that makes ActiveRecord possible, and powerful. With me so far? Things are well-nigh to speed up. We’ve discussed the way that ActiveRecord memorandums yonder databases of individual tables, permitting you to interact with objects representing the data in those tables. What well-nigh making connections across tables? One of the powers of SQL-based databases is their worthiness to combine tables and unriddle data wideness multiple tables, using something known as a “join”). Running joins in SQL can be quite complex, and one of the pleasures of ActiveRecord is the simplicity by which it allows you to join information wideness tables. Returning to theTragedianexample, let’s add some complexity by introducing a whole new kind of thing: books. Just as with our authors, there is a “books” table, which connects to aTypesettingclass. Rows in the “books” table are represented by instances of theTypesettingclass, which we interact with as we would any other Ruby object. What we need, though, is a way for instances ofTragedianto know things well-nigh instances of Book, and vice versa. In the real world, authors write books, and every typesetting is written by an author. There’s a relationship there. As developers trying to model the world, we want to be worldly-wise to represent those relationships. Does ActiveRecord support this? OF COURSE. Extending the ActiveRecord metaphor, we can build relationships among variegated classes by “wiring” them together.  We do this with the ‘has_many’ and ‘belongs_to’ methods. We tell theTypesettingmatriculation that it ‘belongs_to’ theTragedianmatriculation – or increasingly specifically, that every individual typesetting belongs to an individual author. This way, instances ofTypesettingknow how to go to the ‘authors’ table and find their author. Likewise, we tell theTragedianmatriculation that every instance ofTragedian‘has_many’ books – giving instances ofTragedianthe worthiness to go to the “books” table and find their information. A complete, two-way connection requires you to change both classes. If you tell theTypesettingmatriculation that it ‘belongs_to :author’, but forget to tell theTragedianmatriculation that it ‘has_many :books’, then instances ofTypesettingwill know exactly how to find their author, but instances ofTragedianwill have no idea what you’re talking about. Likewise the opposite – if you tellTragedianthat it ‘has_many :books’, but forget to tellTypesettingthat it ‘belongs_to :author’, then instances ofTragedianwill have no problem finding their books, but instances ofTypesettingwill just sort of squint at you uncomfortably. How does this work? Through the magic of foreign and primary keys. Pretty Keys What are these things? They are numbers, stored in your database tables, that tell ActiveRecord how to link variegated classes together. Primary Key: Every table, when you create it, automatically has a post tabbed ‘id’, which holds a unique number, or id, for every new entry in the database. The first entry has an id of 1, the second entry has an id of 2, and so on. This number is known as the ‘primary key’, and ActiveRecord can use this number to find entries in the database, rather than squint things up by their name. Foreign Key: There’s a little voodoo here. A ‘foreign key’ is another post in a table, separate from the primary key or any other post of information, that contains a number which CORRESPONDS TO ANOTHER TABLE’S PRIMARY KEY. I know, I know. This vendible should help you make sense of this. Now, the way ‘belongs_to’ and ‘has_many’ work is that when you tell aTypesettingthat it ‘belongs_to  :authors’, you’re in fact telling aTypesettinginstance to find its foreign key tabbed “author_id” and go and find the row in the ‘authors’ table that has the matching primary key. When you tell anTragedianthat it ‘has_many :books’, you’re telling it to take its primary key and find the row(s) in the books table that has a matching foreign key. That’s ActiveRecord at work. To summarize: ‘has_many’ => take primary key, find matching foreign key. ‘belongs_to’ => take foreign key, find matching primary key. In other words, ‘has_many :books’ is basically saying: “Hey, Author! Yeah, you with the cappuccino. Listen, there’s a table over yonder called ”books”. There’s gonna be a post in it tabbed “author_id” – yeah, named without you. If the number in that post is the same as your “id”, then that typesetting is yours. People might ask you information well-nigh your books, like their name. If anyone asks any of your instances well-nigh typesetting stuff, don’t freak out considering it’s not in your table – just use your instance’s id number to go track it lanugo from the “books” table. Ok?”  Likewise, ‘belongs_do :author’ loosely translates to: “HEY! HEY! BOOK! Are you listening to me? Look. No, really, just be quiet and listen. There’s going to be a post in you tabbed “author_id”. It might not make much sense to you why it’s there, but just wait. If you squint in that closet over there, you’ll find a table tabbed “authors” – right, it’s like the plural version of the main part of the name of the “author_id” post – that’s not an accident. YO! STOP TEXTING. Anyway, if you go to that table, you’ll find a post tabbed “id”. See where I’m going with this? If you take your ”author_id” and throne on over to the “authors” table and find the entry in the table where “id” matches your “author_id”, that’s your author. People are gonna ask you well-nigh your tragedian eventually, and so when they do, that’s what you do.” Alright. Aside: ‘has_many :books’ maps to the “books” table, which makes sense. But ‘belongs_to :author’ maps to the “authors” table, which makes less sense, considering ‘:author’ is singular and ‘authors’ is plural. In cases of “belongs_to”, ActiveRecord knows that it should only vest to one, so it expects you to pinpoint the connection in the singular – but still knows to go and find the match over in the table with the pluralized name. Technology is amazing, isn’t it? Let’s take a peek at some increasingly code, starting with the ‘02_create_books.rb’ migration file. (NB: we number the migration files in sequence considering we expect them to be executed in sequence. This is a topic vastitude this post, but worth reviewing). matriculation CreateBooks < ActiveRecord::Migration def transpiration create_table :books do |table| table.string :name table.integer :author_id end end end So. Notice how in this example, we’ve specified a post tabbed ‘author_id’. That’s where we’ll store the foreign keys. There’s a bit increasingly ActiveRecord intelligence at work here – Active Record knows that ‘author_id’ is a foreign key, meant to correspond to the primary key ‘id’ in the “authors” table. To set up your foreign keys, make sure you include columns in your migration files that follow the pursuit convention: [table name: plural] => [column name: singular]_id. So to link to the ‘authors’ table, you create a post tabbed ‘author_id’. To link to a hypothetical ‘genres’ table (wink wink), you would set up a post tabbed ‘genre_id’. And so on. That’s all you need to do on the database side. Now let’s squint at the classes. Here’s how you set up the ‘belongs_to’ and ‘has_many’ connection: matriculationTragedian< ActiveRecord::Base has_many :books end matriculationTypesetting< ActiveRecord::Base belongs_to :author end Voila. Notice how by defining a simple set of table migrations and towers two very spare classes, we’ve created a tremendous value of functionality. That’s ActiveRecord. There’s more, though. So far we’ve established two kinds of objects (authors and books),  built out the respective database infrastructure, and linked them together. But what happens when we want to expand? What happens if we add a third matriculation of object to our world-model? Let’s try. Let’s add a new kind of thing, genres. First, we’ll toss in a new migration, “03_create_genres.rb”, and fill it with the following: matriculation CreateGenres < ActiveRecord::Migration def transpiration create_table :genres do |table| table.string :name end end end Bam. A “genres” table. Good job. Remember what comes next? Of undertow you do. matriculation Genre < ActiveRecord::Base has_many :books end And we make the pursuit edit: matriculationTypesetting< ActiveRecord::Base belongs_to :author belongs_to :genre end What’s going on here? First, we create a “genres” table, and then built a “Genre” matriculation to bring the “genres” table TO LIFE. We make sure to let the “Genre” matriculation know that there’s a table tabbed “books” that has a post tabbed “genre_id”, and that it can take the “id” of any of it’s instances and throne on lanugo to “books” and squint up all the books that it belongs to. Next, we trammels in with “Book” and let it know that there’s a whole new table, “genres”, that might come a-knockin. We tell “Book” that its table (the “books” table) has a new post (“genre_id”) and that it can take that number and find it’s matching Genre in the “genres” table by finding the genre with the matching “id”. Sounds great, right? But WAIT. WE NEVER ADDED THE “genre_id” COLUMN. Never fear. We can just add flipside migration, “04_add_genre_to_books.rb”, to add a new column. Voila: matriculation AddGenreToBooks < ActiveRecord::Migration def transpiration add_column :books, :genre_id, :integer end end Whew. Now our models should be wired together beautifully. The “books” table has the foreign keys for both the “authors” and the “genres” table. We’re scrutinizingly there. There’s one increasingly bit of sorcery to cover. We have genres, and authors, and books. Books know well-nigh both their genres and their authors, and both authors and genres know well-nigh their books. But what if we want to ask an tragedian well-nigh her genres? Right now, authors don’t have any way of knowing what their genres are – they don’t have any way of matching their “id” up with information from the “genres” table. Only books know well-nigh both. If only… there was… some way… to connect them. But… that can’t be possible. There’s no way ActiveRecord is that sophisticated. Is there? matriculationTragedian< ActiveRecord::Base has_many :books has_many :genres, :through => :books end No effin way. YES EFFIN WAY. Effin Way What the hell just happened. Ok, breathe. Remember,Typesettingcould find information from both the “authors” and “genres” tables. What we’re doing here is using that functionality to create a underpass between “authors” and “genres”. Basically,Tragedianalready knew how to take its “id” and traipse on lanugo to the “books” table to find it’s matching books (by finding the matching “author_id”). What we just did is tellTragedianthat, once it found it’s book, it could go find a post tabbed “genre_id” (which would be right next to “author_id”), take that number, walk a little bit remoter to the “genres” table, and find the genre that matches the typesetting that matches itself. Here’s a summary:Tragediantakes its “id” >> walks on lanugo to “books”, lines up “id” with “author_id”. Scans that same row for “genre_id”, nabs it >> walks on lanugo to “genres”, finds the “id” post that matches the “genre_id” thatTragediannabbed from the “books” table >> gets its genre >> celebration. Now, you might be wondering – does this moreover wire up a connection going the other way? In other words, sinceTragediancan now wordplay questions well-nigh Genre, can Genre moreover wordplay questions well-nigh Author? Let’s walk through it. Genre takes its “id”, and using ‘has_many :books’, pops on in to the “books” table for a bit of tea. While there, it takes a peek at the “genre_id” column, looking for any values that match up with it’s “id”, sooner finding a few. Then… nothing. Genre has no idea that, literally two inches away, is a whole other post tabbed “author_id”, full of succulent goodness just waiting to be accessed. Genre looks around, confused, feeling vaguely uneasy, the stump of some cosmic joke.SoonerGenre slinks home, dejected, and self-soothes by cracking unshut a dusty reprinting of “Watchmen” and thinking well-nigh values and the frailty of mankind. How can we help poor Genre? Try this: matriculation Genre < ActiveRecord::Base has_many :books has_many :authors, :through => :books end Ladies and gentlemen, ActiveRecord. Mad Magazine Fold In, AKA a Join Table Comments Please enable JavaScript to view the comments powered by Disqus. Abacus Abacus kronovet@gmail.com kronosapiens kronosapiens I'm Daniel Kronovet, a data scientist living in Tel Aviv.