Ruby On Rails From Scratch: Week 2

Learn Ruby on Rails from Scratch: Week 2

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…

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.

Ruby Editors

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:

controller start

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:

def view

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:

missing template

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:

view more

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.

HTML skeleton

Save it, and lets test it out again.

test

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.

A Note

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.

Adding Interactivity

Review

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.

Math Time

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:

<html>
<head> <title>Math Demo</title> </head> <body> Will it output 4 +5, or 9?<br /&gt <%= 4 +5 %> </body> </html>

As you can see, it did the math for us:

math

String Concatenation

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.

hello world

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.

Variables

We cannot go any further without discussing variables. For those that have no experience with Javascript, or any server side language, you might not know what exactly a variable is. Think of a variable as something that stores a little bit of information. You can then analyze this data and manipulate it by calling it by its name.

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:

variables

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.

variables

 

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.


Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://Hayesandjarvis.co.uk Andy Farmer

    great tut – first comment!

  • http://www.insicdesigns.info insic

    thanks you for this!

  • http://www.insicdesigns.info insic

    opps! wrong grammar in my first post. I starting to love this series. Hope this will not disappear so sudden like the PHP5 framework. hehehe.

  • http://www.detacheddesigns.com Jeffrey Way

    @Insic – The PHP5 framework hasn’t disappeared. It’s coming out this week.

  • http://www.insicdesigns.info insic

    Thank you for your quick response Jeffrey. Glad to hear that.

    By the way Google chrome looks very nice in this tutorial.

  • http://widgy.net Diego

    Awesome tutorial!
    Keep the good work!

  • Raphael

    praise the lord! part 2 is out!
    thank you.

  • Lukas

    To satisfy my curiosity, What is the text editor in those screenshot?
    Thanks

  • http://www.bloganje.com SpinX

    Great tutorial! And E is really great for windows machines. Which PHP5 framework will you be covering ? I hope it’s Zend Framework. Keep up the good work!

  • http://www.freshclickmedia.com Shane

    Thanks for part 2.

  • http://www.nicktoye.co.uk Nick Toye

    Shame this isn’t presented on OSX, there’s something about writing cool code on a cool machine. Doesn’t quite cut it for me on XP.

    Anyone want to translate?

  • http://www.davidrojas.net David

    Very straightforward tutorial :)
    It would be great if you make another like that about cakephp, a similar framework for php.

  • Phil

    That was a great tutorial!
    I have been waiting for it for what seams for so long time.
    I can’t wait for the next tutorial.
    Keep up the SUPER FANTASTIC work ;) .

  • http://www.furleydelphia.com Furley

    i hope we see a cakephp tut someday

  • anonymous coward

    ruby on vista is like walking on quicksand. get a mac already.

  • http://www.eirestudio.net Keith

    @Insic, Yeah, the framework tut was gone so quick alright.

    Can’t wait to read the article when it comes out, as I remember it is about creating your own php framework.

  • http://shop.supaspoida.com Lar Van Der Jagt

    Just wanted to point out that the extension .rhtml for view files has been deprecated for quite some time now. The new naming convention is filename.html.erb to indicate both the output & the template language.

    When writing about ruby on rails I think it is important to stick with the latest release version. Rails changes very quickly so having the most recent info is key.

    Also, while I understand why you went this way with the tutorial, I think it should be mentioned that throwing a bunch of randomly named actions into your controllers is actually not recommended. As an opinionated framework Rails strongly encourages RESTful patterns, in which you have 7 basic controller actions that can handle all of your Create Read Update & Delete functions. If you find yourself needing lots of custom actions you may be doing something wrong. Of course I can tell the purpose of this tut is just to show how rails passes data from the controller to the view, I just think it should be clearer that you are not meant to start building your applications this way.

    Hope to see some coverage of REST & Resources next week!

  • http://shop.supaspoida.com Lar Van Der Jagt

    Also, a note about Ruby on Windows. Performance is indeed pretty abysmal, which is why I run ruby in & linux VM and just do all my editing on Windows & E Text Editor.

  • http://www.ben-griffiths.com Ben Griffiths

    Another great ruby tut, thanks :D

  • http://jimneath.org Jim Neath

    When I was stuck on a window box and developing Rails, I used to use intype*. It’s free and awesome.

    Or buy a mac.

    *http://www.intype.info

  • http://www.aldrinponce.com weblizzer

    such a great tutorial for this about rails , i’m start to love it now ;) eeheh

  • http://www.1stwebdesigner.com Dainis Graveris

    Now just need to take strike to do those two tutorials, huh, thanks for giving a chance to easy learn ruby :)

  • http://cyberantix.org Connor
    Author

    Thanks everyone for your kind responses…

    Lar Van Der Jagt, This is only an introductory tutorial. When we get into databasing, and applying what we learn to a real world project, then things like that become more important. It still is a bit early ;)

  • http://ha.xors.org Braden Keith

    Very helpful.

    BTW, @Jeremy, the alt text for the nettuts logo in the top left is still PSDTUTS

  • http://www.maxkpage.com Max

    Love it, keep them comin’.

  • http://blogs.sun.com/divas diva#2

    The Ruby-only version of NetBeans is lightweight and has a great Ruby editor with syntax highlighting, code completion, hints and quick tips, as well as integrated IRB console, Rake runner, Test Results output.

  • tominated

    Awesome turorials. They explain it in plain english so I can get to grips with it. Thanks!

  • http://laminbarrow.com Lamin Barrow

    Another good tutorial on getting started with Ruby on Rails. Please keep em’ coming. It has just come to my notice just how similar code in the View page is so similar to the View page code in the new ASP.net MVC Microsoft is developing.

    Here is a little excerpt of view related code i wrote from a new app am developing to show you the similarity.

    <div class="left">
    <%foreach (var post in ViewData.Model.Posts)
    { %>

    <b> <%= post.PostTitle%></b><br />
    Added on <b><%= post.DateAdded %></b> by
    <b><%= post.PostAuthor %></b><br /><br />

    <%= post.PostBody %><br /><br />

    <%} %>

    </div>

  • http://laminbarrow.com Lamin Barrow

    Ops my apologies for the double post. Hey Conor, thanks for writing this tutorials on a windows machine. Don’t let the so call mac faithfuls put you down.

    All hail Microsoft.

  • cam

    BTW Rails 2.0 and 2.1 templates should not be template_name.rhtml but template_name.html.erb so it’s
    template_name . extention . templating_builder, for instance,
    template_name.html.haml is also valid as is template_name.js.rjs and template_name.xml.builder etc etc…

  • http://taylorsatula.co.cc Taylor Satula

    Thanks for part 2

  • http://www.CodeSpanish.com Pablo Matamoros

    Great work Connor!

    Anyone knows what happened with “Learn PHP from Scratch: A Training Regimen”?

  • Steve

    The code sample for the math view has some weird html. It has tags after the closing html and tags that can omly appear in the body before the closing head tag.

    1.
    2.
    3. Math Demo
    4.
    5.
    6. Will it output 4 +5, or 9?
    7.
    8.
    9.
    10.

  • http://cyberantix.org Connor
    Author

    Oh, wow you’re right. Those p tags were actually meant to be outside then spans, but instead were put inside. Ignore the p’s :)

  • lowell

    i’ll be following along as well.. i’m a rails developer myself and i love seeing these tutorials reach out and spread the word and the love.. i just have to remember i’m in a design forum and not a programming forum and to stop cringing every time i see the ‘get a mac’ comments lol..

    lar’s on point with the linux vm solution, especially if you’re pretty entrenched in windows.. it is ridiculously fast.. you may not be able to use textmate, but gedit all souped up is a BEAST!

    @david.. isnt cake essentially a port of of rails from ruby to php? ive only heard of it, havent played in it.. php doesnt like me. actually every lang that isnt ruby or objc hates me.. but thats for my own blog lol..

    @nick.. every f****ng rails screencast out is _in_ os x, no need for ‘translation’.. this was actually a nice break..

    @connor.. great work..

  • http://www.crysfel.com crysfel

    there is an eclipse plugin for ruby language, and it is for free.

    i test the plugin on windows, linux and mac, and it runs very well :D

  • http://vailo.wordpress.com Niklas

    Ahh wonderful! The second part! I finally got InstantRails to install on my Vista 32x machine, haven’t been able to run it with Vista 64x yet. Have to agree with Insic about the PHP framework series also, will be a great read to!

  • http://www.image2markup.com Ivan

    @anonymous_coward: Not everyone has cash for a Mac ;)

    Glad to see the second part, was wondering will it ever show! Can’t wait for the next one.

  • http://www.tomstardustdiary.com Tom

    Very nice step-by-step guide.

    I’m following your tutorials, it would be good to see a new post every 2-3 days and not every week ;)

  • Tomas

    This is great, but for beginners screencasts are generally easier to follow.

  • http://www.detacheddesigns.com Jeffrey Way

    @Tomas – Definitely. Rest assured, I’m working on it!

  • Sabandija

    really really really nice tut… I hope they don’t stop coming ;)

  • http://widgy.net Diego

    Awesome tutorial, just digged it!

    I’d love if you post it mosre fastly… or put little challenges for the next week lessons, so we can practice the thing we learn…

  • Luke Faccini

    Thanks! I’m loving to learn RoR can’t wait for the next week!

  • http://minardimedia.com minardi

    cool tuto!

    I was looking for it just a long time. I don’t know if you have any experience using flex + rails for creating whats now its known as flexible rails. I am new with both so it would be cool if you couls show how to meet this guys together. I have read very interesting things can be done using flex as frontend and rails for backend functions.

    Keep the great work!

  • Presbyran

    Nice tutorial!
    Keep them coming! :D

  • http://yvesvanbroekhoven.mxml.be Yves Van Broekhoven

    Straight forward tutorial.

    Like Diego said, some challenges are not a bad idea.

    Keep it coming!

  • Pingback: Arbenting’s Best of the Week (09/07 - 09/13) | Arbenting

  • http://widgy.net Diego

    Hey, where is the part 3 ?
    I’m just mad about it!

  • http://www.detacheddesigns.com Jeffrey Way

    @Diego – Hopefully, it should be coming this week!