Rails MVC for absolute beginners, or … how do I find the html file?


This post is about the Model-View-Controller design pattern that supports the entire Rails framework. It is made for the beginners, for those curious people that went through one or two basic Rails workshops, but never learned how the parts of the framework communicate to each other. Usually on RailsGirls events you have an opportunity to create your own application but depending on the coach and your interest, you may not get it fully. Keep on reading, this might help you to understand better where is your controller action, model or the view that is rendered …huh? Let’s start!

Design patterns in software engineering are highly recommended snippets of code that are based on the good practices, this is a simplified definition and for now you don’t need to know more. MVC, or Model-View-Controller design pattern is just one of them. This one is so awesome because it allows us to separate the logic of the domain, presentation and the flow, or its cases, by putting them into 3 places. You might find this as complicated to understand but let’s see how does it work on the example.

Assuming you used the tutorial for building your first Rails application available on the official pages of the RailsGirls you have the directory structure shown on the image below.

Everything that belongs to the controller layer is placed in the controllers folder. Besides the initial one, application_controller.rb, we have our ideas_controller.rb. Inside this file you will notice the basic CRUD methods: we have index, show, new, edit, create, update and destroy. Those actions allow us to have a different flow of actions depending on what the user wants. The good practice is to keep those and reuse them as you need. However, sometimes you might need to expand it with your own methods which is also possible. We will see an example later on.

Another layer contain models, so we have the models folder with one model named ideas.rb. This file is responsible for the logic of the domain, or at least it is a good practice to use it having this in mind.

The last one, the one that is the most important for the user is of course the views layer located in views/ideas folder. Generated folder contains index, edit, new, show and form files. Notice that the last one, _form.html.erb starts with an underscore, this means that this file is a partial. It is a part of the view that can be reused in different main views. Index, new, edit and show are on the other hand the main views.

Ok. But what does that mean for you? Well, next step is to understand how the things work. Let me try to simplify it. Whenever user types an url, that url leads to something. How to find that something? Well, let’s first find our routes. On the Terminal (or Command Prompt for Windows users) type:
rake routes
The output might be something like:

How to read this? You have Prefix, Verb, URI pattern and Controller#Action.
Prefix is the way the specific url is named in the application. If you actually use in the code ideas_path or ideas_url you will get the full path or url as it is shown in the URI pattern for the first line: /ideas(.:format). Format specifies the request that is done, for now, remember it is html what the browser wants. As you continue, you will find out there are more formats such as js, json, xml… Another thing to notice is the part that starts with semi column “:id”, this means that the url will have an id of the record.
More, whenever a browser calls for the http://localhost:3000/ideas (assuming you are in the development mode), application will call for the ideas#index, or if we read it: ideas_controller # index action. The column that remained is the Verb. I won’t go in deep explaining what verbs are, you can find more information about it on Open Sourcery.

Imagine controller is a big boss that knows how the things should work. It manages the rest but does not really care how. Controller action that was called specifies how the request should be handled. The big boss, controller, has two great friends that are helping him out, model and the view. However, model and view don’t really like each other because of different interest so controller has to mediate between them. Also, controller does not bother himself talking to the database, nor database wants that. In order to get some data from the database and show it to the user, controller action first calls the model. Here is the index action:

# GET /ideas
# GET /ideas.json
def index
  @ideas = Idea.all

The line with the Idea.all is the call to the model, it retrieves all the records for Idea. So retrieving was delegated to the model and model and database with the help of ActiveRecord came up with some records and those are returned to the controller. You might notice that there is no definition for the method all, that is correct, that part is the ActiveRecord thing. He knows more about that.
Further, controller is so nice and caring to store those in the object variable, that variable that starts with @, which makes it available for the view. So controller action calls the view named the same as itself – index.html.erb and provides the view with the collection of ideas that were retrieved from the model.
The responsibility of the view then is to show those records to our user. In order to improve the view with new labels, paragraphs or other contents, in this case we should change the index.html.erb file.

Next time, when you wonder what action is called, first check the rake routes in order to find the controller action, then see how is it defined and the good practice is to named the view with the same name. If you respect this convention (based on the MVC design pattern) you can make your life easier. As I already mentioned, sometimes you do need slightly different action and in that case you can extend your controller with something new. Still, be careful not to increase the complexity of the controller with no reason.

Imagine we want to make a random generator page for our ideas. We are bored and we want a great idea, that is the purpose, how to approach this problem? (Notice, there are many approaches and here will be presented one that follows the process above)

First, we can make a url that goes to what we want. We have to add another route to the application and we will do that by adding a route to the config/routes.rb file:

resources :ideas do
  get :random_generator, on: :collection

We specified the /ideas/random_generator route, on collection means that no id will be sent and the url will start with ideas/… Now, if we run rake routes we get the following:

We have our url, that goes to the ideas controller # random_generator action, so let’s create one, add the following to app/controllers/ideas_controller.rb :

def random_generator

This method itself only requires the random_generator.html.erb view so let’s create one. Inside app/views/index create and save a new file with the name: random_generator.html.erb. If we really want a random idea form the database we have to make controller actually talk to the model so we add call to the random_generator action and now it looks like:

def random_generator
  @idea = Idea.get_one_random

This time, ActiveRecord has no idea what is get_one_random so we have to specify it. Go to the app/models/idea.rb and add definition:

def self.get_one_random
  r = Random.new
  total_count = self.count
  find(:first, offset: r.rand(total_count)) if total_count > 0

This method allows us the retrieve the idea from the specific position based on the generated number if there are some records. Notice that we call self., this means we specified it is a class method. The method should be called like Idea.get_one_random.

The record that is returned to the view is stored to @idea. Now controller can send this to the view and view can show it however he likes, for example, knowing that our Idea has the following attributes: name, description and picture we can have the following code in the app/views/random_generator.html.erb:

<h1> Random generator!!</h1>
<p> The super awesome random idea you wanted to see is: <p>

  <%= @idea.name %>

  <%= @idea.description %>

<p>You better use it wisely!!</p>

<%= link_to 'Edit', edit_idea_path(@idea) %> |
<%= link_to 'Back', ideas_path %>

And here it is! A working example for our application. We successful extended the basic behavior respecting the MVC design pattern. Now challenge yourself and create your example! Try to list 10 random records, or list the last 20, or come up with something more original! Good luck!
Happy coding! ;)


Ruby on Rails? …how can I get in?


Last week I had an opportunity to be a part of Rails Girls Hamburg workshop. Even though it wasn’t my first experience introducing people to Rails, it was my first real coaching experience where I definitely learned a lot.

The event started with an installation party and continued with one day workshop of making stuff. As usual, those workshops first follow the tryRuby and then another tutorial for creating very simple Rails application. A couple of lightening talks where presented and the day ended with a barbecue on the roof terrace of one business building in Hamburg. Lovely.

But this post is not about the event. It is about how to get into Rails when you know …very little, and your gender is not doing you a favour. What I saw in Hamburg last week was a room full of curious girls, with different backgrounds, that want to explore the world of programming and making web applications. That cruel world of software engineering where the men still have the main lead and where female programmers are sometimes treated as less worthy or capable. But why? I saw a lot of potential there, a lot of very smart girls trying to find their way to this exclusive world.

How to start?

As a female software engineer that is in this world for three years already, I can tell you the following:

  • Do not fear!
  • Be curious!
  • Learn and learn, do not dare to stop!
Now let’s elaborate one by one, trust me, they are really important.

Do not fear!

Fear of what you might ask? As I already mentioned, software engineering world is dominated by men. They know everything and they are sure in their knowledge, but let me tell you a secret, it is barely the attitude. There is no person out there that knows everything. Women do tend to be more insecure in many ways and knowledge is just one of them. It is particularly hard in the beginning, as a beginner you don’t know much and when you ask something to your colleague, the probability of less structured response is higher than if the question was asked by men. You might encounter  this, but it is not actually an issue. There are a lot of tutorials, books and other contents that can help you.
You only need the right sources and here is my advice.

Follow one of the online schools, from all of them out there I highly recommend CodeSchool. Unfortunately this one is not for free but it is much better than all the rest. And no, they are not paying me to say this. I say it because I tried many and this one is definitely No.1! Within one month you can get very good base to continue or even advance knowledge if you get really into it. So, CodeSchool.

The harder way is following the tutorials and manuals of each one of the technology and this is what you need:

  1. The very basic or how everything starts
  2. Learn how to make your site beautiful by learning CSS, CSS3, SaSS, Javascript and jQuery
  3. Learn how to work with Rails
  4. Learn how to take advantage of the Ruby programming language
  5. If you will have questions, you can always ask google or find it directly on:

Be curious!

Ok, you learned how to make a website using Ruby on Rails but the game is not over. There are so many interesting fields left to explore. Test Driven development, software architecture and design patterns, security, software quality, performances and optimisation, software development processes, managing requirements, software configuration management and many many more! Be curious and explore!

Learn and learn, do not dare to stop!

Well, this one says for itself. It is a never ending field, with a lot of space for improvement! You will spend hours and hours figuring out things, but the reward once you solve a super-complicated problem, that “I did it!”, is indescribable!

Software engineering- men world?

This does not seem so difficult, right? Everyone can do it! Still a very simple question asked by one of the attendants made me think a lot lately. The question was something like: “Ok, you are in this area for three years already, why do you think this field is more “for men”? Why there are not so many female software engineers?
I do not have an answer for this one, you can ask me anything about Ruby, Rails, software architecture… but this one, this one is quite hard. I have no idea. Maybe because we are raised to be beautiful, sensitive, nurturing, dependent, self-critial and graceful creatures. But let me tell you another secret, we can be all of that and more!
My research on this topic is still not done. But so far, our early ages drives us away from any form of engineering and science. With the toys we have, the way our parents treat us and much more.

What I can tell you, men are not born with this knowledge, they got it through hours and hours of playing around with technology and exploring, just follow their example! Find some geeky girls around you and joined them. Rails Girls is present in more or less all bigger cities and those girls are more than happy to help you with whatever you need. Just find the closest one to you or connect with someone through Linkedin, Github or other networks.

Take the challenge! Trust me, it is worth it!

PS: A big thank you to organising team of Rails Girls Hamburg- I had a great time! Hope to see you around!

PPS: If you want to help me and my friend in developing our super secret project please do not hesitate to contact me! It is for fun only, no money rewards, just to make it clear! ;)

Happy coding! ;)


Git: how to fix your own stupidity?


I guess everybody have experience in deleting files that were not supposed to be deleted and this time git cannot help us, there is no returning to specific commit because we just did… something stupid. What am I talking about?


git add . 
git reset --hard

So we were doing something, we added some new files that we plan to use in the future, but the code we changed does not work and we just want to start from the last commit. So we simply do a reset. Wait! What? What about committing those files? …ups, they are gone!

No they are not, git is awesome! Why?

git fsck --lost-found

fsck verifies the connectivity and validity of the objects in the database and by sending the flag –lost-found we write the dangling objects into .git/lost-found/other/. If the object is a blob, the contents are written into the file, rather than its object name.

Our files are now “back”, we can find them:

ls .git/lost-found/other

Well, file names are lost but you have the content, what else can you wish for? :)

Problem resolved thanks to Stack Overflow thread.

Happy coding! :)