The Dark Side of Ruby on Rails

Author profile picture
Ruby on Rails framework (RoR) is the dream of each and every developer. It does just about the whole lot for you with out a lot effort, and while you be told it and deeply are aware of it, you’ll construct a whole web site in a pair of hours (After all, styling this is a other tale). The exhausting section of rails is to grasp the magic in the back of it. 

For this text, I can think that you’ve got a powerful basis on Ruby (particularly OOP), that you’ve got rails put in on your gadget (if you do not, simply run:

gem set up rails
on your terminal), and that you recognize what the MVC style is and the way it works (It is a nice reference to start out if that is the primary time you could have heard of it or when you aren’t very acquainted).

Since construction a easy web site the use of Ruby on Rails is really easy, apparently in the beginning nearly like magic. You’ll simply run on your terminal:

rails new weblog
cd weblog
rails g scaffold submit identify frame:textual content
rails db:migrate
rails s

With the ones five traces for your terminal, you’re going to have an absolutely running internet application that may can help you Create, Learn, Replace, and Delete (C.R.U.D.) posts that experience a identify and a frame. And not using a unmarried line of code! This is simply how superb RoR is.

However how?! What simply took place? How did RoR do this?! How can I’ve keep watch over over that? What goes on in the back of the scenes? Neatly, we can expose the entire secrets and techniques and solution all the ones questions proper right here and now.

Once I began studying Ruby on Rails, I used to be following The Odin Undertaking; the primary mission they ask you to construct is a Weblog app discovered on the Jumpstart web site. This is a unfastened and rather well defined educational that guides you step-by-step, however what it fails to do is to explain what goes on. We can be the use of it as a walkthrough throughout this text in order that we will be able to unveil the secrets and techniques of RoR, so let’s get began!

The very first thing that we can wish to do is create our app, so move forward and observe the academic, and I can meet you proper after Growing the Article Fashion

The Fashion

Good enough, so what simply took place? Neatly, you simply created a migration that may create a MySQL desk named Articles. In case you have by no means heard about SQL, this is a relational database control device language. Wow, grasp on! That sounds intimidating. You’ll learn slightly bit about SQL right here, however do not dive in too deep, so far as you remember the fact that a database is the place we’re going to retailer our customers’ knowledge (together with articles, posts, and so on.) and that SQL is the language our app will use to be in contact with it, you can be advantageous for now.

There are lots of other SQL databases; we have now PostgreSQL, MySQL, TSQL, and others. Rails default is SQLite, you’ll move on your root record listing and into Gemfile, and also you will have to have the ability to see one thing like this proper on the best:

supply ''git_source(:github)  ""  ruby '2.6.5' # Package edge Rails as an alternative: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 6.0.3', '>='
# Use sqlite3 as the database for Lively Recordgem 'sqlite3', '~> 1.4'

That remaining line is the gem that tells RoR which sort of database to make use of, and you’ll simply trade it simply by converting it to:

gem 'pg', '>= 0.18', '< 2.0'

To switch it to a PostgreSQL database, however let’s depart it as is for this text, I simply sought after you to bear in mind that there are different choices. RoR will create the database proper for your gadget; it’s going to make the gap, configure it, and depart it able so that you can upload tables, upload rows to tables, and create relationships among tables. Now transfer on during the Running with the database segment, and I can meet you proper after.

Good enough, so let’s dive slightly bit deeper into what we simply did. In our earlier segment, Growing the Article style we arrange the basis and ready Rails to create a desk in our native DB. On this segment, we’re making the migration to create that desk.

We’re specifying that we need to create a desk referred to as articles, with a column named identify, and each and every worth of that column goes to be a string and every other column referred to as frame, which can have a textual content worth. The distinction between a string and a textual content is the quantity of chars that each and every one can care for. Textual content will have to be used when there are a number of traces and String when there are going to be only some phrases or letters.

We will have finished all this in one step after we created the style the use of:

rails g style Article identify frame:textual content

We should not have to specify the string on identify as a result of it’s the default worth. Then we will have simply run on the terminal:

rails db:migrate

Emigrate our desk to the database, but it surely was once a just right workout to know the way to construct a desk and the syntax for how you can specify the column names and sort.

We now have now completed growing our first desk for our weblog, the Article desk. We will now upload articles to the database manually (Since we should not have an interface but to try this). To paintings with the database manually, we use the Rails Console.

It’s an interface that may permit us to speak to the DB and the DB simplest! The maximum essential directions for the use of the console are:

Creates a brand new Article, BUT IT DOESN’T SAVE IT TO THE DB.

Article.create( identify: 'Pattern Article Identify', frame: 'This is the textual content for my article, woo hoo!')

Creates a brand new Article, AND IT SAVES IT TO THE DB INSTANTLY.

You’ll additionally assign a brand new row of the DB desk to a variable i.e.

a =

And you’ll then get admission to the desk columns:

a.identify = 'Pattern Article Identify'
a.frame = 'That is the textual content for my article, woo hoo!'

After which you’ll save that example into the DB.

You’ll additionally learn out of your DB:


Returns the entire articles for your DB.


Returns the item that was once created first within the DB.


Returns essentially the most not too long ago created article within the DB. finding(1)

Will have to go back the item with the identity 1. The identity is one thing we had now not mentioned right here but. Each and every component within the database has an identifier referred to as by means of default NAME_OF_THE_TABLE_id on this case, article_id. This worth is exclusive and is incremented by means of 1 for each and every new row stored within the database. You’ll get admission to each and every explicit row the use of this identity, and it’s what we can use to hyperlink components from one desk to every other later on (For instance, to grasp which articles belong to which person, we might upload a column to articles referred to as user_id which can comprise the identity of the person who wrote them. Since it’s distinctive, it’s going to by no means be unclear who wrote what).

Now that you recognize what the console is, what each and every instruction does, and what’s in it, let’s do the following two sections of the academic Running with a Fashion within the Console and Having a look on the Fashion; and I can meet you proper after.

The Routs

Now, we’re going to transfer to the Routs. You’ll assume of the Routs because the boss within the MVC structure; it’s the one that may obtain the directions and ship them to the proper position in order that the person can get the request responded. If you happen to ever wish to trade the best way a request is interpreted or the place it will get despatched, you’ll have to communicate to it. In case you have forgotten our MVC style, here’s a reminder:

For this segment, we think that you’ve got a minimal wisdom of HTTP requests. If you don’t, I strongly counsel you undergo this educational first. The House, Evaluate, Requests, and Strategies sections are a very powerful ones to grasp for now. An excessively transient abstract of those portions that you just will have to perceive is that as our MVC style displays, a browser receives and sends “one thing” from/to different elements. We name this the requests, and each and every request comes with one way. The two primary strategies are GET and POST.

GET is when the browser asks for one thing (For instance, a sign_in shape), and POST is when the browser sends one thing (For a similar instance, when it sends again the sign_in shape crammed out and the Controller has to do one thing with it). However grasp on, How does RoR know the place to ship each and every request? I imply, I simply mentioned that when it has a sign_in shape crammed out, or a Put up shape crammed out with a identify and a frame, how does it know what to do with it? Neatly, the routes are those that take care of this good judgment.

It may well “learn” the HTTP request that the browser sends and assign the proper Controller to paintings it with directions incorporated, simply as a md would ship an order to get processed to the proper division.

The subsequent segment of the academic explains it higher than I ever may, so let’s transfer on, that is sufficient advent so that you can get a greater draw close of the following segment: Putting in the Router so move forward and do this and I can meet you simply ahead of Growing the Articles Controller.

The Controller.

You’ll assume of the Controller because the manufacturing facility the place the request is processed. As soon as the Routes obtain the request from the browser, it reads it and assigns a Controller to procedure it. Then it’s going to use the directions from the Routes to visit the database to get the guidelines it asked and procedure it to ship it to the View.

As you noticed within the earlier segment, the Routs learn the HTTP cope with, and it is aware of which Controller to ship the request. The Controller is the place your magic will are living; you’re going to create the Database rows, save them, and practice any set of rules you want to them.

You’re going to pay attention so much in regards to the CRUD movements; what CRUD stands for is:

  • Create
  • Learn
  • Replace
  • Delete

And we’re going to do this with nearly anything else we create on RoR. For the Articles we’re running on, we’re going to Create articles, permit customers to Learn articles (display the articles to them), Replace (edit) them and Delete them. The Controller is the one this is going to be doing this for us. This is a Elegance, and we can create an example of it on call for.

As with every elegance, it’s going to have strategies that may be public or personal and example variables. Now you are prepared, move forward and whole the Growing the Articles Controller and Defining the Index Motion sections, and I can meet you simply ahead of Making a Template.

The View

The View is the tip of our procedure, what we’re going to render to our person, the articles the person requested for us to turn, or to edit, or regardless of the person asks us to do, ends with a view. At the moment we face an error. Here’s the MVC once more:

We created the Fashion, we arrange the DB and the Routs, we created our first motion within the Controller, however we’re lacking the View, and that’s what RoR is looking us for, it does now not have a template. We’re going to dive into some deep stuff, so get relaxed.

The browser is creating a GET request (you’ll take a look at it on your cope with bar on your browser, http://localhost:3000/articles/ now, sort on the terminal: 

rails routes 

Remember to use a distinct terminal from the one that you’re the use of to run your server. You’re going to see that the /articles(.: layout) is a GET request, it’s learn by means of the routes and despatched to the best Controller (Articles Controller), since that HTTP request particularly asks for a definite motion (Once more, move on your terminal, and you’re going to see that the Controller#Motion column is assigned for that HTTP request.

You’ll trade this motion if you need! This is past the scope of this educational and article, however needless to say you’ll, since it might be helpful while you get started coping with sign_in, sign_out, and any motion out of the CRUD ones. Are you able to wager the place you could possibly trade that? If you happen to guessed Routs you might be proper! The Routs inform the Controller what motion to accomplish, so you would need to trade it there.), after which the Controller, by means of default appears for a view with the similar identify because the motion it simply carried out.

Once more, you’ll trade this simply by redirecting to the proper trail you need it to head, however we can dive into that later. For now, I simply sought after to you should definitely had been following the waft. Browser -> Request -> Routes -> Controller -> View. Ahead of I set you unfastened and will let you whole sections 10 and 11, I need to introduce you to every other thought you want to grasp and obviously perceive. It’s the params hash.

Params is a hash that transports knowledge from the View to the Controller. Let me display you our MVC once more:

You’ll see that View has a two-way side road that connects to the Controller, however how do I ship one thing from the view to the Controller? Neatly, that’s the params hash! Pass forward and watch this video on what the params hash is and the way it works. This is it; you might be all set to finish the remainder of segment 10 and segment 11.

The subsequent section is most likely essentially the most an important section of any MVC mission you intention to construct, the associations. What an affiliation is, is the best way you’re going to make the family members between 2 fashions. Needless to say we simply made a complete Articles MVC? Neatly, we at the moment are going so as to add feedback to it.

How are we going with the intention to inform which remark belongs to which submit? What if a submit has many feedback? Neatly, needless to say we talked ahead of in regards to the identity’s and that we might use them to hyperlink two other fashions in combination? Neatly, now’s the time. Ahead of shifting on to segment 12, watch those movies:

Now, create a brand new account on and take a look at to make the ERD diagram of the Articles and Feedback, the place a piece of writing could have many feedback, an author_name box, and a frame box. What’s going to be your number one key? What’s going to be your overseas key?
What’s the cardinality that you are going to have for the connection? I constructed an ERD for this dating for you if you happen to get caught. Now that you’ve got an concept of what it’s that you need to construct, let’s transfer on to segment 12 and create the MVC for Feedback, and structure the associations. Please come again to this text ahead of segment 13.

Many-to-many relationships

Good enough, so you could have come a ways, congratulations! You might have constructed a practical internet app, and most significantly, you know the way RoR is doing it! This subsequent step goes to turn us how you can create complicated associations. Up to now you could have constructed a one-to-many dating the place a piece of writing has many feedback, however what occurs if in case you have a many-to-many dating?

Consider your Fb pals.

You (the person) have many pals, however you might be additionally a pal of many different customers! A many-to-many dating is exactly that. Consider how you could possibly construct it for a 2nd (Do not spend an excessive amount of time on it! This is a exhausting one to be your first technique to it). Pass forward and skim this text.

Be happy to seek for as a lot details about this as you want, that is one of the hardest-to-grasp and maximum essential ideas about MVC, however do not get hung up on it since apply would be the highest instructor. If you’re feeling able, move forward and take a look at so as to add this subsequent affiliation on your ERD diagram. We’re going to create tags for our posts.

A submit could have many tags and a tag may belong to many posts. A tag will have to have a reputation and will have to be associated with articles thru a Tagging helper desk that are meant to comprise the ids of each, Articles and Tags tables. I can now not give you an answer this time, however after getting an ERD that you’re feeling pleased with, move forward and do segment 13 of the academic. If you end, return on your ERD and make the best corrections if you’re feeling you could have some spaces for development.

In conclusion, Rails isn’t natural magic; it simply does so much for us in the back of the scenes. The toughest portions to get the draw close of are the HTML requests since RoR makes use of some the right way to be in contact the browser with the Controller and it holds so much of knowledge (like params, cookies, consultation, and so on.), the routes, and the associations.

I am hoping this text was once useful to you, and I am hoping you did not attempt to do all of it in 1 hour as a result of some of those ideas require so much from you to grasp them and have the ability to practice them accurately.

You’ll at all times succeed in out to me thru LinkedIn or Twitter when you get caught someplace, I can perhaps have some extra references to percentage with you that can assist you get thru no matter problem you might be going through, and I’m at all times as much as Zoom with any aspiring device developer who wishes a hand. 

See you on the opposite facet! Glad coding!


The Noonification banner

Subscribe to get your day by day round-up of best tech tales!

(Visited 1 times, 1 visits today)

Leave a Reply