So, you learned a bit of Ruby and decided to take a trip down the Rails
to test out your mastery of your new language skills. You get
yourself a ticket with a
rails new ProjectName
and arrive at the station, only to find it filled with strangers and doors and hallways and no idea where to go to get your project off the ground. Well, the best place to go when you’re lost in a busy place is the Information desk so off you go! As you walk up to the counter you notice this big stand full of pamphlets, marked GEMS and they look exciting. You haven’t been on holiday in a while and all these tourist attractions are so interesting, even if they aren’t
always that much fun in the end. If you had more time, you think to yourself, you’d try out every single one of them but not today. No, today you just have to figure out how to get around this station and find your way on one of the coming trains. As you approach, you see the word ‘Guides’ on a little sign sitting in the middle of the desk.
“’Scuse me, miss, could you tell me where to go?”, you ask.
“Of course I can,” she beams, “where would you like to go?”
“Oh, I’m not too particular. You see, this is my first time and I just
want to go somewhere”, quietly pleased with yourself at such an
agreeable answer.
“Well, you’re free to go anywhere you like then. Continue on and you’ll
find yourself somewhere!”
She walks off as you wonder to yourself what just happened when a short, little man in an overcoat tugs on your jacket sleeve.
“You seem to need some help” he smiled, revealing a missing tooth.
You nod and he starts dragging you over to a darkened hallway with a
bright little gift shop just on the outside. As you start to question your decision to follow, he pipes up.
“This is the old mall. Look”, he beckons with a dirty finger poking out
of a too-long sleeve. “It’s a mighty big place and the lights are about all out now, so watch yourself. Mostly just pipes and cables running the place over in the bin. The rest is basically just storage and rent spaces”.
You lean a little closer and make out some dusty names above the shop. You think you recognize a couple like lib, log, storage, tmp, and vendor.
“Of course, it might get built up again one day, that’s up to you” he
continues, almost whispering the last bit, “but in the meantime, there’s still the gift shop.”
As you get pulled in by the sleeve, you see the store is called ‘Public’. Inside the shop the most amazing, ridiculous, useful, interesting things can be found. There’s a corner full of posters and other images ranging from the Mona Lisa to a finger painting made by Lisa Moon. Text files, Word documents, and Excel sheets take up the two farthest walls while the wall nearest you is covered in different font types. Just as you feel yourself getting lost in all the things you imagine finding in the public folder, you snap back to reality with the pull of your jacket sleeve leading you back out.
“Let’s not get too carried away, we should only put static shareables in here”, and as you wonder what he means by ‘us putting’ things in there you find yourself back in the hustle and bustle of the main station, only to be greeted by a man in a nice suit with a full smile.
“Where did the m..” you get cut off.
“Where’d the man go? Oh, he scurried off somewhere. I’m here to get you to administration. Follow me”
Compelled by curiosity and confusion, you find yourself following the man,
still no more sure of where to go than when you began. Suddenly you find yourself in front of a place with the sign ‘DB’ printed in large letters across the side of the building.
“This is the bank. Things are a little different here and we use a different currency than you’re used to. Remember this. The bank only takes one thing, object instructions, and you must withdraw these objects using time. The less time, the better. It’s simply business.”
He opens the door, just enough to peek in, and you hear a bunch of what
sound like accountants, clacking away at calculators and punch machines. Closing the door, he continues.
“We have two main database systems for you to consider, SQLite3 or PostgreSQL.”
“Ok, so if I wa..”, cut off again.
“The bank manager will answer your questions later. My job is to guide you
to administration. These markers along the way are only to serve you
when you get to administration. Let us continue.” and we were off
again before I could object.
“The office to your right is where research and development are conducted. There are two main teams leading our R&D and you will find their offices listed as either test or spec. Personally, I like Rspec but MiniTest has its merits, as well. That will be a question for you to decide.”
“Why for me to decide?”, I look at him but of course my confusion is met
with silence.
“The config office to your left handles all of the basic configurations you see around us. The environment desk handles the air conditioning, lighting, and other things that affect the surrounding area for both your comfort and the public’s.”
Speaking as briskly as he walks, we go inside, and immediately it feels as if
you’ve stepped into a government office. There are offices along a hallway and a single desk in the center of an open room covered in documents.
Leading you to the desk, he continues, “You shouldn’t need to do much work at this desk just yet. The offices will take some time before you need to be concerned with them either. For now, the only things you need from the config office are two documents. The database.yml will be needed when you speak to the bank manager and the routes.rb file will be needed when you speak to The Controller. Please pick them up and proceed to your office. Your meeting with the bank manager will be there later this afternoon.”
“My office?”, I inquired.
“Yes, your office, did you not see it outside? Here, it’s right next to this one.“ he says with a sigh, pointing through the window to a nice little glass office space with a very modern-looking sign above it and the word “App” boldly slanting across it.
Thankful to get away from that curt gentleman, you pick up the documents and head towards the glass office building he pointed out, thinking to yourself how much you like the sound of the little bell as you open the door to leave.
Pausing just outside the app office door and looking back around, you notice you’ve started to recognize some of the places you’ve already come across and feel this Rails station to be much less crowded now. The shadowy place with the gift shop, the data bank, the testing office, and the config office all seemed interesting but you still didn’t know what to do here yet. Well, those gems did look fun.
“Welcome back sir!”, a cheerful voice breaks into your thoughts and you
realize you’ve been getting stared at by a young, almost too peppy, receptionist, causing you to blink in silence.
“Welcome sir, I’m so glad to see you! I’m so excited to get to work! What
can I do to help you?”, she squealed and you swear you heard a glass shatter somewhere.
“Well uhh...you see, I’m new here and I don’t know where to go but I
want to get on Rails. I’ve seen all sorts of things but still, no one has told me where to go”
“That’s because that’s MY job! This is the app office and this is where all the action happens. This is where you decide where to go and how to get there! Come on, let me show you around!”
With a smile, you follow the little spot of sunshine.
“OMG, this is going to be so much fun! Ok, so, assets and Javascript. These are pretty easy, right? Assets are where your stylesheets and other processed files are served into the pipeline. Javascript used to be in assets but it's grown too big so it was given its own access to the pipeline. Naturally, this is where your JavaScript will go. These help style HTML and make it more interactive, so on to the HTML! That’s the views office. It also handles JSON and other formats but we’ll worry about those later.
For now, the HTML. Just like any HTML document, it’s only for substance. You have more flexibility when you use ERB, and you may be tempted to just put all your code into one document but if you start doing that, it makes for one big file and costs others their jobs. It’s not nice so we’ve decided to keep only the actual structure of the project there.”
She opens a door and interrupts what looks like a board meeting.
“This, however, is the helper office,” she continues unfazed “they handle all the logic that happens in your HTML pages. Any functions or decisions that need to be made can go through them and they’ll return your variable any way you tell them to. There are already a bunch in here but you can make your own and add them too!”
“So the view logic goes in the helpers and the actual view HTML is for calling those methods?”
“Yooouuu GOT it!!”
“Great! So now I can just build an HTML page and get on my way, right?”
“Not yet! You still have to meet the models!”
“Models, you say?”, with a little grin, you think this might be a fun office
after all.
As she opens the next door in the hallway, the sound of hammers against
chisel rises out and you see some people on one side of the room
carving different sculptures.
“Yep, the models! Well, more specifically, the Active Recorder, she...”
You lose track of her voice as the most beautiful thing you’ve ever seen comes into view, just across the room. As if the heavens themselves parted and from it, the single most amazing thing you’ve ever seen sat highlighted in its glow. A sandwich that was, at once, every sandwich you’ve ever drooled over, and yet you couldn’t think of a name for it other than just Sandwich. You feel drawn to it, almost magnetically, but right before you reach it, the receptionist pulls you away.
“..and so yea, as I was saying, this is the Active Recorder. She can build anything you can imagine. I have yet to see her stumped!”
“Welcome!” she smiles, “I look forward to building some great stuff for you!”
“I’ll do my best” you stammer still thinking of that sandwich, “and
who’s that gentleman in the corner looking like a librarian?”
“Oh that’s the bank manager!” your receptionist chimes in.
“That’s my husband.” the Recorder adds and waves him over.
“Ah yes, I have a meeting with him!
“Precisely why I’m here,” the bank manager says gently, reaching us just at the right moment. “It is fortuitous that my wife would be here as well. Is now a good time?”
“Perfect timing, as always!” your receptionist calls out, clearly enjoying her occasional interjections.
With a small chuckle, he continues, “I’ll be as brief as I can be. As I have already been introduced, I am the bank manager. I manage the database here. I believe you have a file for me?”
“Yes right here”, you tell him, handing over the database.yml file.
“Wonderful, this file will come in handy if you ever need to change banking systems from SQLite to PostgreSQL. This won’t be necessary for building your apps but if you plan to deploy your app to Heroku, the transition will become vital. If you would like to avoid such hassles in the future you can begin your new project with the addition of –database=postgres, as in
rails new Project –database=postgres
. However, as you have already initialized us with the SQLite database system, we will proceed for now. You can read this to learn about how to make the swap if you so desire. With me so far?”Taking a pamphlet from him, you ask, “Ok so I don’t really need to worry
about this database.yml file unless I’m using PostgreSQL?”
“Correct! Now on to the next part, and why I’m happy the Recorder could be here as well. You see, we work together, she creates the objects and migrates them to me where I store them. Any time you wish to create something new and make it available to the world, you need to create a model of it. As you see, the artists here are all taking the model sandwich
you saw before and creating instances of it. Note the subtle differences though. This one has bologna, and that one has ham. I think I saw a tuna and a salami with mustard over there as well. While each one is different, they are all the same type of object, based on their model. That is the Recorder’s job. My job is to keep a record of each of these active instances. I am here to catalog and store each version of this model object for as long as you need it. This way you can ask me for a ham sandwich on rye bread with swiss cheese any time you want and I will know exactly which variation of this sandwich you’d like me to send you.”
“Sounds awesome but I don’t know how to create new objects yet”
“I can help with that,” the Recorder says, “To generate a new model, simply say, ‘rails generate new model IceCreamSundae container:string flavor:string scoops:integer toppings:string’”. In the blink of an eye there was suddenly a marble statue of the most delectable, yet indistinguishable ice cream sundae I had ever seen and at the exact same time, there was a new document in my hand.
“What is this?”
“That is a migration file”, the bank manager explains, “that is the file that tells me how to store this new object model. When you are finished creating your new object, you will migrate that file into my hands.”
“Ok, so now what do I do?”
“Now, for what I really do”, began the Recorder, “You’ve decided to create an object and you’ve given it a few variables, such as flavor and toppings. I assign restrictions, or validations, to these variables and other sets of rules. I can say that every Ice Cream Sundae MUST have toppings or that an Ice Cream Sundae flavor must be at least 3 letters long. I can also reference the strawberry flavor against a list of other flavors or the cheesecake topping against a list of all available toppings through associations. Once the list of features your object needs is set and the rules are outlined by me, you need to send that migration file to the database. From there, the bank manager takes it to the vault and incorporates it into the schema, where all the object models are kept in tables.”
“You are not to go there!”, the bank manager huffed.
“No?”, you queried.
“Absolutely not; you do not adjust the schema file. If you wish to make any changes you will go through the proper channels and submit a migration that changes the schema like everyone else. Just because you own the project doesn’t mean you can do what you want.”, he quipped, gruffer than
you would have expected from him.
“Let’s see then, would you like this Ice Cream Sundae in a bowl or a cup?”
the Recorder asks.
“Cup, please,” you tell her.
“What flavor ice cream, how many scoops, and what toppings would you like?”
“Strawberry, 2, and cheesecake crumbles.”
Suddenly, there shimmering before you like a mirage, was an Ice Cream Sundae in a cup, with two scoops of strawberry ice cream and cheesecake
crumbles on top.
“Ok, I think I get it so far. So I create the model to list the rules and associations my object has and I use the migration file to spell out its column names and file types? I give the migration file to the database and it gets put in the schema. Then I can create as many types of that object as I want and they’ll be stored in the database. Yes?” you ask, though as you’re speaking you’ve already created a few more instances of sundaes.
“Exactly!” they both nearly shouted.
“Great. So now that I can create objects, how do I actually get an instance
of one? I’m hungry!”
“Easy, you just call upon it in the view!” the Recorder offered.
“Well it’s not as easy as all that,” the bank manager added “you remember the two types of exchanges the bank does, right? You deposit objects through the migrations, which you just did, and mak withdrawals using time. That time comes from the Controller. Furthermore, just as I must take your deposit to the schema myself, I also can only return your withdrawal to the Controller. He calls upon the objects you wish to use in your view and it is from him that you will receive your object.”
“Well then let’s go see him!”
At that, you bid farewell to the Active Recorder, and your receptionist,
and follow the bank manager to the Controller. Leaving your office, you notice the config office and remember the routes.rb file.
“What was this for again?” you ask, holding out the routes.rb file.
“Ah, so glad you still have that!” the bank manager exclaimed, “the
Controller will need that. Hold on to it.”
He continues to lead you past the testing office, back into the main station. With the admin offices behind you and the shadowy area on the other side of the station, you notice a big center office before you clearly marked ‘Controller’ and wonder if you somehow missed it before. You had to have nearly bumped into it turning around from the Information desk earlier.
“So this is where it all happens,” you said to no one in particular.
“Yep, this is where it all happens!” the bank manager looked pretty
pleased being here. “Let’s go in!”
Leading you through the door of this columnar structure, rimmed at the top with windows, a frenzy of beeping and blinking immediately attacks
the senses.
“What is all this?!” you cry above the racket.
“This is where it all happens. This is the central hub for everything you see and do!”, a voice shouts, “All this racket is coming from requests sent to us for the database. It doesn’t have to be this loud in here but the less efficient your requests, the more connections I need to make and it tends to get out of hand. Do you have any idea how time-consuming it is to call up each and every object every time I want to check one aspect of it? It eats up more than a greedy puppy with a spilled bag of kibble, I tell you what!”
You look around for the bank manager but he seems to have disappeared in the haze of blinks, beeps, and confusion. All you can see around you are cables and plugs and lights across desks and boxes plugged into walls. A shadow on the other side of the wall catches your attention. Then from behind you: “Well, what is it? I don’t have all day you know, I have lots to do!”
“Uhh...I’m here to see the Controller? I have a routes.rb file for him.”
“Well come on around then! Let’s go, you’re wasting time. I hope you’re
here to do more than waste my time.” you finally pinpoint the voice as coming from behind one of the desks and as you peer around the side of it you see the smallest man you’ve ever seen in your life. He couldn’t have been more than a meter tall. Meter and a half, maybe. “Well come on, out with it, what can I do for you then?”
“Hi!” you hesitate “I’m new here and uhm, well I wanted to go somewhere with Rails but I’ve been around and around the station and I’ve been told which places to leave alone, how to create objects, where to bring files to and still no one has told me how to get anywhere but here I am. I have one more document and I’m told it goes to you. If I’m going to get more run around though, I might as well just head home.”
“Well alright now, hold your horses, wait a second there.” Suddenly he
seemed a little more patient. “So you’ve been run around and don’t know anything anymore but you just want to get somewhere in Rails, right?”
“That’s right.”
“Alright, well come with me. It’s about time I had a lunch break and I’ll fill you in on the rest of what’s going on.”
He says to no one in particular,
rails
generate
controller Diner index
and walks you out of the controller room to the station diner, talking all the while.“..so you see, it’s really quite simple. Everything you’ve been learning so far has been the back end of the Rails system. Not learning that is like packing for a camping trip without knowing if you’re going to the beach or the mountains. Choosing the right database to work with, setting up your database file if necessary, creating models for the objects you want to use, setting rules and associations in the models, and migrating those designs into the schema to set up the database for the project is how you create things behind the scenes. What I do is help connect those things from the back end to be used in the front end.”
The two of you enter the diner and it’s way bigger than you were
expecting. Spying a booth in the corner, you both take your seats. The waiter, professional to a tee, is already at your table with menus. After listening to him read off the specials for the day, the Controller continues.
“Now you know why I’m so busy!”
“I’m starting to see it. So, tell me again. What’s the front end?”
“Well, it’s...it’s everything! Everything you see around you! Take this
station for example. This is your Rails app. That means the dining room we’re sitting in is in the View. Watch, hand me that routes.rb file.”
After taking it from you, he begins to erase something on it called
‘resources :diner’ and suddenly you find yourself in the middle of the
station, clearly able to see the people all around.
“Now,” he said, “let’s add the diner back in. The HTML is still there.
If you look at just the index file, you could see the diner sitting there but it would just be you and the code. Adding a route to it makes it come alive. This is the structure, the backbone of our Rails app. This is our view”
You see him write
resources :diner,
only
: %i[index]
and you find yourself back in the diner, although somehow different. Then it dawns on you. Everything is quiet. There are no customers, no staff, no register. Only tables and chairs and windows and walls.“First off, we created a route.” He pointed to the words on the page. “This allows us to find our view inside the Rails station by assigning resources to it. Right now we’ve only included the index page, which is where we are sitting. This won’t do though, there’s not enough here”. He pulls out another piece of paper and you see the words ‘Diner Controller’ at the top. He begins scribbling on it and when he sits back you see in a block marked for ‘index’ that he’s created a variable.
“You see this variable here? This is a connection established between the
database and the view. You query the database and assign whatever it returns to a variable by saying something like @staff = Staff.all or @staff = Staff.find_by(job: ‘Waiter’). Now, the diner knows how to make add a waiter to the view.” and as if on cue, you notice the waiter suddenly appear, wiping a countertop.
You ponder for a moment before replying.
“Ok, so I created an Ice Cream Sundae model, listed the rules for making a sundae in the model, and migrated the design of that sundae, with all its variables, to the schema. Then I created an instance of that sundae and stored it in the database with a name like ‘Strawberry Cheesecake’ sundae. Now I can create a variable in the controller block for the page I want to use it in, such as this index, which will query the database for this sundae and make it available here in the View?”
“That’s correct!”
Taking the Diner Controller document you continue, “Then I can add @sundae_menu = Sundae.all to this index method and ...”
Appearing before you could even finish your sentence was a menu listing the Strawberry Cheesecake, Banana Split, Double Fudge, and Apple Pie
sundae you created earlier, along with all the ingredients you assigned to each.
“Now do you see? Look at everything around us. Each item has to be queried and it’s exhausting! Look here, see this?” he asks, thrusting a
printout of the server log.
“Every variable you call in the view, and every time you call it, I have to
send another query to the database. This is the heart of the N + 1 problem. Now, listen closely. Eager loading your associations can clean this up but if you forget, it puts a LOT of work on me!”
“I get it. I’ll be careful!” you insist, as he begins packing up.
“Well, that’s all the time I have, for now. I have lots of work to do and
it’s time for your trip!”
“Time for my trip…? Oh, right! Yes, let’s get to it!” you jump out of your seat and follow him out of the door, back to the controller room.
Walking in the door, you notice everything is much quieter.
“Yes, yes, I’m sure you’re noticing the change.”, already behind the panel again, the controller’s voice comes from some unseen source, “This is what it could look like in here when you handle the N + 1 problem. Everything runs faster and smoother! Got it?”
Nodding, he appears again and begins ushering you towards the exit.
“Well good, it’s time to head back to the station then. When you get out there, walk up to the tracks and give it this command,
rails
server
. Your train will arrive shortly. From there, simply set your own root in the routes file, point it to your controller index and be sure to have something in the corresponding view. All the variables from your controller will be available in that HTML. Hop aboard and good luck!!”“Thanks!”, you call out, but he’s already gone again, “Wow, he seems so busy but there are so many ways to query the database, I’ll be sure to ask for exactly what I need.”, resolutely saying the last bit as you head towards the tracks, more to yourself than anyone else.
You find yourself standing in front of the train door and think how great it is when the train door stops right where you’re waiting. Looking back over all the different areas of the station you saw today, you notice a few other places that you missed, like the Post Office, a room marked ‘Cables’, and a line of people in the back waiting in line for ‘Jobs’. Maybe next time you’ll stop and peek inside. For now, it’s off to visit the world on Rails!
Lead Photo by Thomas Lefebvre on Unsplash
Also published at https://defoebrand.medium.com/take-a-ride-on-the-rails-hop-on-the-mvc-5a35f0424f1f