Start a hosting plan from $3.92/mo and get a free year on Tuts+ (normally $180)
Welcome to Ruby on Rails From Scratch Week 2. Hopefully this sequel to week 1 will help to further your education in Rails. This week, we'll do a little bit more with getting an actual page up and running. We'll also work on adding more interactivity by embedding ruby in HTML and learning a little about variables. After that, we'll learn more about Ruby's beautiful URL structure and how to manipulate it, plus other things as well. This is definitely going to be a packed week!
Last week, we got the framework set up, and learned a little bit more about ruby and rails. We then learned how to create a new application and generate a controller.
Now that we're going to get into Rails Syntax, we need a good editor. Since rails is a relatively new framework, it doesn't have quite the range of syntax supported editors. Luckily, there are still extremely good ones out there. For windows, I personally use E Texteditor. It has great support for ruby, and features automated scripts for many languages. E text editor branched off of the success of the exclusive mac program TextMate. The only downside to both, are that they aren't free. If you're looking for something free, you could always go with the reliable Notepad ++.
Getting Things Visible
Creating an Action
As you might remember from last week, we ended by creating a controller which we called learn. This will lead us into today's tutorial. We are now going to use that controller, and create an action in the controller. We will then also create a corresponding view file. The view is the component of MVC architecture that usually contains all of the HTML, and therefore is an embedded ruby file (rhtml).
Now that we have the learn controller generated, we can view the rb file by going to app/controllers/learn_controller.rb. Right now, you should see the following code already there:
This default code allows this controller to inherit the default application controls.
We now need to define a method, specifically, an action. This action will map out the URL for the view. To define an action named more, we type the following code:
We can pick any name we want. A good strategy when picking the name of the action, is giving it a name that has to do with the content that will be there. You should also pick the name according to the desired URL. The controller and action map out the URL. For example, to get to the "more" page, you would type in, localhost:3000/learn/more. In fact, let's try it and see what happens:
Oops...as you can see from the helpful error message, we still need to make a view.
Creating a View
Unlike the controller, to create a view we do not need to generate it through the console. Instead, we can simply create a new file. When we generated the controller, learn, you might have seen that a directory (called learn) was created in the app/view folder. We need to create an .rhtml file inside there, and call it the action that we defined in the controller.
A picture's worth a thousand words, so here you go:
And now, just to test out the page, we'll add a little HTML and see what happens. I just added a basic required HTML, and then some dummy text and title. You can put anything you'd like here.
Save it, and lets test it out again.
Great it works! Congratulations, you created your first page in Rails. Although it's not much now, you now have a basic understanding of how to create a basic rails application.
Ruby on Rails has some paradigms that it follows. For example, normally, when you are building an application in rails, when you generate a controller, you capitalize it and make it singular. Although we didn't capitalize the current controller we are working with, it is a good habit to get into when you are building real applications. I remember when I was learning Rails for the first time, it frustrated me that all of the tutorials I read, mentioned a paradigm here and there, but never listed all of them in one place. I don't want to do the same to you! But, if I explained them all now, it wouldn't sink in as well, as if you knew more about each component. So don't worry about it too much now, and I'll explain it later in this series.
Last week, we learned how to embed rails code into an rhtml file. If you remember, a <% -%> is processed code, but doesn't include anything that will actually be outputted to the user. On the other hand, <%= %> code will be outputted.
You can do math easily with ruby. For this example, I created a new action in the learn controller called math. We are going to do some simple math which will be embedded in tags above. Here is what we will type:
<p><html><br /> <head> <title>Math Demo</title> </head> <body> Will it output 4 +5, or 9?<br /> <%= 4 +5 %> </body> </html> </p>
As you can see, it did the math for us:
You can create a string in ruby by using quotes. You can even combine strings together by concatenating them together. There are several ways to do this. The most logical, is to treat it like math:
<html> <head> <title>String Demo</title> </head> <body> <%= 'This is kind of boring' %><br> <%= 'Will I combine' + 'With You?' %> </body> </html>
When we output this we show how exact ruby is though. Notice there is no space between combine and with. To add a space just add one before the quote at the end of combine or before with.
How Important is the = and - sign?
They are both very important. I mention this again, so you clearly get their purpose. The equal sign determines if the user sees it or not. If we were to revisit that last bit of code and take out the equal sign from both of the snippets, we would just have a blank page. Now, if you are assigning a variable or something that doesn't physically output anything, then don't put the = sign,
The - sign is not necessary, but a good habit to get into. If you're not using the = sign, then put a - sign, when you're closing the embedded ruby. This eliminates the white space that would otherwise be inserted into the code. This can, in very rare cases, mess up the project.
Assigning A Local Variable and Displaying It
Assigning a local variable is quite easy. Here is how you would assign it and then display it. You could do this in one line, but I'm showing the difference between embedded processed ruby and embedded and shown ruby (The equal sign thing again :) ):
<html> <head> <title>Variable Demo</title> </head> <body> <% text = 'This is a Variable' -%> <i><%= text %></i> </body> </html>
And here you can see the result:
Assigning An Instance Variable and Displaying It
The problem with local variables, though, is that they're...local. What if we need to assign a variable in the controller, and display it in the view? That's where instance variables come in. An instance variable is set apart from a local variable by the @ sign which is put before the name. Please note that both instance and local variables (as well as most other kinds) cannot have capital letters and no spaces.
To demonstrate how we can pass dynamic content between the controller and view, we will first have to insert code into the learn controller. By now I have added more definitions for all of the above demos. Here is the current learn controller. As you can see, I have assigned an instance variable in the variables action. When the user requests that action, Rails looks up the definition, processes it, and sends it to the view (In this case, the value of the variable):
class LearnController < ApplicationController def more end def math end def strings end def variables @text = 'Why Hello' end end
Now we're going to reference the variable in the view:
<html> <head> <title>Variable Demo</title> </head> <body> <i><%= @text %></i> </body> </html>
Sure enough, the variable is passed to the view.
Next Week and Final Words
This week we learned about setting up actions in controllers, defining views, local, and instant variables. I hope that you found it all helpful! Next week, will be even more exciting. I plan on finishing up the basics of the interaction of the controller and view. Hopefully we will also have time to learn more rails techniques too! After that, it just gets more exciting! (Ruby syntax, working with databases, scaffoldings, etc.). Anyway, if you have any questions, be sure to let me know; and I'll be sure to get back to you!
Like always, please Digg this if it helped you!
- Subscribe to the NETTUTS RSS Feed for more daily web development tuts and articles.