<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Nettuts+ &#187; Ruby</title>
	<atom:link href="http://net.tutsplus.com/category/tutorials/ruby/feed/" rel="self" type="application/rss+xml" />
	<link>http://net.tutsplus.com</link>
	<description>Web Development &#38; Design Tutorials</description>
	<lastBuildDate>Fri, 20 Nov 2009 19:56:34 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Essential Learning for Ruby and Rails</title>
		<link>http://net.tutsplus.com/tutorials/ruby/your-ruby-library-essential-reading/</link>
		<comments>http://net.tutsplus.com/tutorials/ruby/your-ruby-library-essential-reading/#comments</comments>
		<pubDate>Tue, 25 Aug 2009 15:41:32 +0000</pubDate>
		<dc:creator>Dan Harper</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[ruby on rails]]></category>

		<guid isPermaLink="false">http://net.tutsplus.com/?p=6457</guid>
		<description><![CDATA[<img src="http://nettuts.s3.amazonaws.com/417_ruby/images/postimg.jpg" alt="Your Ruby Library: Essential Reading" />]]></description>
			<content:encoded><![CDATA[<p>Ruby is rapidly becoming the preferred programming language for many developers. With that said, let&#8217;s look at some of the best tutorials, videos and books to learn Ruby and Rails.</p>
<p><span id="more-6457"></span></p>
<h3 style="clear: both;">Beginner Resources</h3>
<p>Just starting out with Ruby or Rails? Take your pick:</p>
<ul class="webroundup">
<li>
<div><img width="165" border="0" src="http://nettuts.s3.amazonaws.com/417_ruby/images/ruby.png" /></div>
<h4>Ruby Programming Language</h4>
<p>Ruby is&hellip; A dynamic, open source programming language with a focus on simplicity and productivity. It has an elegant syntax that is natural to read and easy to write.</p>
<p><a href="http://www.ruby-lang.org/">Read More</a></p>
</li>
<li>
<div><img width="165" border="0" src="http://nettuts.s3.amazonaws.com/417_ruby/images/railsguides.png" /></div>
<h4>Getting Started with Rails</h4>
<p>Install Rails, create an application, using databases, the principles of MVC and RESTful design &ndash; this is an essential resource for getting started with Rails and learning the best practices.</p>
<p><a href="http://guides.rails.info/getting_started.html">Read More</a></p>
</li>
<li>
<div><img width="165" border="0" src="http://nettuts.s3.amazonaws.com/417_ruby/images/15minblog.png" /></div>
<h4>Creating a Weblog in 15 minutes with Rails 2</h4>
<p>In 15 minutes, we go from scratch to complete weblog engine with comments, ajax, an ATOM feed, an XML and JSON API, tests, an administrative interface, and much more! We strongly advise that you sit down before starting this whirlwind tour. Your head may well be spinning at the end. Come along for the Ruby on Rails ride.</p>
<p><a href="http://rubyonrails.org/screencasts">Read More</a></p>
</li>
<li>
<div><img width="165" border="0" src="http://nettuts.s3.amazonaws.com/394_ciRuby/images/postimg.jpg"/></div>
<h4>From CodeIgniter to Ruby on Rails: A Conversion</h4>
<p>In this tutorial, you will learn the basics of Ruby and Rails through direct comparisons with your existing CodeIgniter and PHP knowledge.</p>
<p><a href="http://net.tutsplus.com/tutorials/ruby/from-codeigniter-to-ruby-on-rails-a-conversion/">Read More</a></p>
</li>
<li>
<div><img width="165" border="0" src="http://nettuts.s3.amazonaws.com/417_ruby/images/peepcode.png" /></div>
<h4>Rails 2 From Scratch series</h4>
<p>PeepCode sell very high-quality, useful screencasts covering most aspects of Rails. This 76 minute screencast teaches you the basics of Rails. If you&#8217;ve done PHP, ASP, Perl, or any other type of web development and want to learn Rails, this is the screencast for you.<br />
		Available in two parts, for $9 each. They are definitely worth the price.</p>
<p><a href="http://peepcode.com/products/rails-from-scratch-part-i">Read More</a></p>
</li>
<li>
<div><img width="165" border="0" src="http://nettuts.s3.amazonaws.com/299_ror/200x200.jpg"/></div>
<h4>Ruby on Rails for Designers</h4>
<p>Take a brief look into the world of Rails with this fantastic tutorial available here at Nettuts.<br />
			Ruby on Rails is an open-source web framework that&#8217;s optimized for programmer happiness and sustainable productivity. It lets you write beautiful code by favoring convention over configuration.</p>
<p><a href="http://net.tutsplus.com/tutorials/ruby/ruby-on-rails-for-designers/">Read More</a></p>
</li>
<li>
<div><img width="165" border="0" src="http://nettuts.s3.amazonaws.com/057_rubyOnRailsFromScratch/200x200.png"/></div>
<h4>Learn Ruby on Rails from Scratch: Series</h4>
<p>Ruby on Rails&hellip; by now most people have heard the hype about it. It promises more effective code, total object orientation, and true MVC architecture to say the least. As far as my own personal experience, it has been all that and more. The code is beautiful, easy to maintain, and edit. In a recent project I was working on, it took me less than 10 hours to do the application, as compared to at least double that if I was writing in PHP.</p>
<p>
			<a href="http://net.tutsplus.com/tutorials/ruby/learn-ruby-on-rails-from-scratch-week-1/">Week 1</a>, <a href="http://net.tutsplus.com/tutorials/ruby/ruby-on-rails-from-scratch-week-2/">Week 2</a>, <a href="http://net.tutsplus.com/tutorials/ruby/ruby-on-rails-from-scratch-week-3/">Week 3</a>, <a href="http://net.tutsplus.com/videos/screencasts/ruby-on-rails-week-4/">Week 4</a>
		</p>
</li>
<li>
<div><img width="165" border="0" src="http://nettuts.s3.amazonaws.com/417_ruby/images/apple.jpg" /></div>
<h4>Using Ruby on Rails for Web Development on Mac OS X</h4>
<p>This article introduces you to Ruby on Rails by building a trivial web application step by step. Consider it a ride on the express train‚Äîan overview of what Rails can do, including a look at features new to Rails 1.0. In the end you&#8217;ll be better equipped to consider the advantages of powering your web application with Rails.</p>
<p>It&#8217;s slightly dated, but the core techniques are still in use.</p>
<p><a href="http://developer.apple.com/tools/rubyonrails.html">Read More</a></p>
</li>
<li>
<div><img width="165" border="0" src="http://nettuts.s3.amazonaws.com/417_ruby/images/peepcode.png" /></div>
<h4>REST For Rails 2</h4>
<p>Another screencast from PeepCode, available for $9. This screencast covers the basics of REST and walks through a simple application to show how REST routes work. You‚Äôll learn about the magic that goes on behind the scenes and how you can design a REST application with confidence.</p>
<p><a href="http://peepcode.com/products/rest-for-rails-2">Read More</a></p>
</li>
<li>
<div><img width="165" border="0" src="http://nettuts.s3.amazonaws.com/417_ruby/images/rails-php-web.png" /></div>
<h4>Rails for PHP Developers</h4>
<p>If you&#8217;re proficient with PHP, you already have the essential skills needed to build web applications. This site will present an ongoing discussion of techniques for learning Rails and Ruby from a PHP perspective.</p>
<p><a href="http://railsforphp.com/">Read More</a></p>
</li>
<li>
<div><img width="165" border="0" src="http://nettuts.s3.amazonaws.com/417_ruby/images/peepcode.png" /></div>
<h4>TextMate for Rails 2</h4>
<p>Yet another PeepCode screencast, this is an essential if you&#8217;re developing Rails applications on a Mac. If you own a copy of TextMate but wish you were more familiar with the most frequently used keyboard shortcuts, this screencast will help orient you with what&#8217;s possible.<br />
		As with all PeepCode resources, this is available for $9.</p>
<p><a href="http://peepcode.com/products/textmate-for-rails-2">Read More</a></p>
</li>
</ul>
<h3 style="clear: both;">Advanced Resources</h3>
<p>Already have a good footing with Ruby and Rails? Try these:</p>
<ul class="webroundup">
<li>
<div><img width="165" border="0" src="http://nettuts.s3.amazonaws.com/417_ruby/images/railscasts.png" /></div>
<h4>Railscasts</h4>
<p>Every week Ryan Bates will host a new Railscasts episode featuring tips and tricks with Ruby on Rails. These screencasts are short and focus on one technique so you can quickly move on to applying it to your own project. The topics target the intermediate Rails developer, but beginners and experts will get something out of it as well.<br />
		Prefer text tutorials? Check out the next item:</p>
<p><a href="http://railscasts.com/">Read More</a></p>
</li>
<li>
<div><img width="165" border="0" src="http://nettuts.s3.amazonaws.com/417_ruby/images/asciicasts.png" /></div>
<h4>ASCIIcasts</h4>
<p>Railscasts (above) is the #1 resource for quickly learning new Rails tricks. If you prefer text tutorials over video, ASCIIcasts is for you!<br />
		ASCIIcasts are detailed, illustrated text versions of each Railscast, each with a link to the original video.</p>
<p><a href="http://asciicasts.com/">Read More</a></p>
</li>
<li>
<div><img width="165" border="0" src="http://nettuts.s3.amazonaws.com/417_ruby/images/railsforum.png" /></div>
<h4>Rails Forum &ndash; Tutorials</h4>
<p>A round-up of short tutorials covering a huge range of Rails techniques, from beginners advice and installation to debugging and tests.</p>
<p><a href="http://railsforum.com/viewtopic.php?id=6790">Read More</a></p>
</li>
<li>
<div><img width="165" border="0" src="http://nettuts.s3.amazonaws.com/345_forum/preview.png"/></div>
<h4>Building a Forum From Scratch with Ruby on Rails</h4>
<p>Today, we will be building a simple forum using Ruby on Rails, and we will be working up from the basics covering things like authentication and more advanced database techniques.</p>
<p><a href="http://net.tutsplus.com/tutorials/other/building-a-forum-from-scratch-with-ruby-on-rails/">Read More</a></p>
</li>
<li>
<div><img width="165" border="0" src="http://nettuts.s3.amazonaws.com/417_ruby/images/envycasts.png" /></div>
<h4>Envy Casts</h4>
<p>Envycasts is the screencasting side of Rails Envy, a partnership between Gregg Pollack and Jason Seifer. However, not all the screencasts you&#8217;ll see here are Rails related.<br />
		You&#8217;ll find several fantastic video tutorials covering a number of Ruby techniques and best-practices, most available for only $9.</p>
<p><a href="http://envycasts.com/products">Read More</a></p>
</li>
<li>
<div><img width="165" border="0" src="http://nettuts.s3.amazonaws.com/417_ruby/images/scalingrails.png" /></div>
<h4>Scaling Rails</h4>
<p>Learn everything you need to know about Scaling your Rails app through 13 informative Screencasts produced by Gregg Pollack with the support of New Relic.</p>
<p><a href="http://railslab.newrelic.com/scaling-rails">Read More</a></p>
</li>
<li>
<div><img width="165" border="0" src="http://nettuts.s3.amazonaws.com/417_ruby/images/peepcode.png" /></div>
<h4>RSpec Series for Rails 2</h4>
<p>This 55 minute screencast is the first of a 3-part series on RSpec. You&#8217;ll learn how to install and configure RSpec. We&#8217;ll walk through a simple project. Then we&#8217;ll install RSpec in a Rails application and start writing examples for a simple model.<br />
		If Test::Unit doesn&#8217;t make sense to you, or if you want to write better code, this is the place to start.</p>
<p><a href="https://peepcode.com/products/rspec-basics">Read More</a></p>
</li>
<li>
<div><img width="165" border="0" src="http://nettuts.s3.amazonaws.com/360_rails/200x200.png"/></div>
<h4>Getting Started with RESTful Authentication in Rails</h4>
<p>In this article, we will use restful_authentication to add a user system to a simple Rails application. This is great for those first starting out and need step-by-step directions for using this amazing plugin. At the end of the article, visitors will be able to create an account, reset their password, login, logout, and validate email addresses.</p>
<p><a href="http://net.tutsplus.com/tutorials/ruby/getting-started-with-restful-authentication-in-rails/">Read More</a></p>
</li>
<li>
<div><img width="165" border="0" src="http://nettuts.s3.amazonaws.com/417_ruby/images/peepcode.png" /></div>
<h4>Rails 2.1 PDF</h4>
<p>For over a year, Ryan Daigle has kept you informed on the latest updates to the Rails trunk. In this new 80-page PDF, Ryan discusses over a dozen new features in Rails 2.</p>
<p>Code snippets and examples show you how to use many new features in Rails 2. A section on deprecated features suggests third-party alternatives.<br />
		Available for $9 from PeepCode.</p>
<p><a href="http://peepcode.com/products/rails-2-pdf">Read More</a></p>
</li>
<li>
<div><img width="165" border="0" src="http://nettuts.s3.amazonaws.com/417_ruby/images/peepcode.png" /></div>
<h4>Ruby on Rails Code Review PDF</h4>
<p>If you&#8217;re a beginning Rails developer, this is the book for you! Seventeen chapters show how applications are often written (the wrong way). Then, we show you how it should be done correctly.</p>
<p>It&#8217;s more than just a checklist, it&#8217;s a tour of well-built applications that will help you build rock-solid web applications.<br />
		Available for $9 from PeepCode.</p>
<p><a href="http://peepcode.com/products/rails-code-review-pdf">Read More</a></p>
</li>
</ul>
<h3 style="clear: both;">Ruby Books</h3>
<p>Prefer to have a book to-hand when learning? Here&#8217;s a collection of some of the best Ruby books around:</p>
<ul class="webroundup">
<li>
<div><img width="165" border="0" src="http://nettuts.s3.amazonaws.com/417_ruby/images/pickaxe.png" /></div>
<h4>Programming Ruby &ndash; the PickAxe</h4>
<p>Affectionately known simply as the &#8216;PickAxe&#8217; in the Ruby community (due to the PickAxe on the cover), this is almost Ruby&#8217;s de-facto official book. A must-have for any serious Rubyist!<br />
		The First Edition of the PickAxe is available for free at <a href="http://www.rubycentral.com/book/">Ruby Central</a>.</p>
<p><a href="http://www.pragprog.com/titles/ruby3/programming-ruby-1-9">Read More</a></p>
</li>
<li>
<div><img width="165" border="0" src="http://nettuts.s3.amazonaws.com/417_ruby/images/poignantguide.png" /></div>
<h4>Why&#8217;s (poignant) Guide to Ruby</h4>
<p>Written by Ruby&#8217;s very own crazy-genius, why the lucky stiff (or _why), this is a free and very unusual guide to the language. Take a read through the first few pages, and you&#8217;ll see why this book is a massive success.</p>
<p>_why&#8217;s entire online presence recently disappeared, suddenly, and so the link below is to a mirror of the book, or you can download the <a href="http://www.ember.co.nz/resources/whys-poignant-guide-to-ruby/">PDF version</a>. The book was originally available <a href="http://poignantguide.net/">here</a>.</p>
<p><a href="http://mislav.uniqpath.com/poignant-guide/">Read More</a></p>
</li>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/417_ruby/http://nettuts.s3.amazonaws.com/417_ruby/images/chunky-bacon.png" border="0" /></div>
<li>
<div><img width="165" border="0" src="http://nettuts.s3.amazonaws.com/417_ruby/images/rubyproglang.png" /></div>
<h4>The Ruby Programming Language</h4>
<p>Bestselling author David Flanagan teams up with Ruby creator Yukihiro &#8220;Matz&#8221; Matsumoto and writer/cartoonist/programmer why the lucky stiff to bring you the authoritative guide to Ruby. Covering versions 1.9 and 1.8, this book helps you learn Ruby&#8217;s lexical structure, primary expressions, conditionals, syntax, classes, the data it manipulates, and more. For experienced programmers who want to look at this language in depth, this guide is invaluable.</p>
<p><a href="http://oreilly.com/catalog/9780596516178/">Read More</a></p>
</li>
<li>
<div><img width="165" border="0" src="http://nettuts.s3.amazonaws.com/417_ruby/images/rubyway.png" /></div>
<h4>The Ruby Way</h4>
<p>The Ruby Way takes a &#8220;how-to&#8221; approach to Ruby programming with the bulk of the material consisting of more than 400 examples arranged by topic. Each example answers the question &#8220;How do I do this in Ruby?&#8221; Working along with the author, you are presented with the task description and a discussion of the technical constraints. This is followed by a step-by-step presentation of one good solution. Along the way, the author provides detailed commentary and explanations to aid your understanding.</p>
<p>This book is not recommended for beginners to Ruby, however.</p>
<p><a href="http://www.informit.com/store/product.aspx?isbn=0672328844">Read More</a></p>
</li>
<li>
<div><img width="165" border="0" src="http://nettuts.s3.amazonaws.com/417_ruby/images/everydayscripting.png" /></div>
<h4>Everyday Scripting with Ruby</h4>
<p>Everyday Scripting with Ruby is divided into four parts. In the first, you&#8217;ll learn the basics of the Ruby scripting language. In the second, you&#8217;ll see how to create scripts in a steady, controlled way using test-driven design. The third part is about finding, understanding, and using the work of others &ndash; and about preparing your scripts for others to use. The fourth part, more advanced, is about saving even more time by using application frameworks.</p>
<p><a href="http://www.pragprog.com/titles/bmsft/everyday-scripting-with-ruby">Read More</a></p>
</li>
</ul>
<h3 style="clear: both;">Rails Books</h3>
<ul class="webroundup">
<li>
<div><img width="165" border="0" src="http://nettuts.s3.amazonaws.com/417_ruby/images/agilerails.png" /></div>
<h4>Agile Web Development with Rails</h4>
<p>This is where most Rails developers started, and the book is now in its third edition to cover the ever-changing framework.<br />
		&#8220;Rails 2, released in 2008, brings hundreds of improvements, including new support for RESTful applications, new generator options, and so on. And, as importantly, we&#8217;ve all learned a lot more about writing Rails applications in the last few years.&#8221;</p>
<p><a href="http://www.pragprog.com/titles/rails3/agile-web-development-with-rails-third-edition">Read More</a></p>
</li>
<li>
<div><img width="165" border="0" src="http://nettuts.s3.amazonaws.com/417_ruby/images/railsway.png" /></div>
<h4>The Rails Way</h4>
<p>Like &#8216;The Ruby Way&#8217;, this is not a book for new-comers to Rails.<br />
		&#8220;Using detailed code examples, Obie systematically covers Rails&#8217; key capabilities and subsystems. He presents advanced programming techniques, introduces open source libraries that facilitate easy Rails adoption, and offers important insights into testing and production deployment. Dive deep into the Rails codebase together, discovering why Rails behaves as it does &ndash; and how to make it behave the way you want it to.&#8221;</p>
<p><a href="http://www.informit.com/store/product.aspx?isbn=0321445619">Read More</a></p>
</li>
<li>
<div><img width="165" border="0" src="http://nettuts.s3.amazonaws.com/417_ruby/images/rails-php.png" /></div>
<h4>Rails for PHP Developers</h4>
<p>This is the perfect book for PHP developers wanting to explore Rails.<br />
		&#8220;Rails for PHP Developers kick-starts your Rails experience by guiding you through learning both Ruby and Rails from a PHP developer&#8217;s perspective. Written by developers with deep experience using PHP, Ruby, and Rails, this book leverages your existing knowledge of PHP to learn Rails application development quickly and effectively.&#8221;</p>
<p><a href="http://www.pragprog.com/titles/ndphpr/rails-for-php-developers">Read More</a></p>
</li>
<li>
<div><img width="165" border="0" src="http://nettuts.s3.amazonaws.com/417_ruby/images/rails-net.png" /></div>
<h4>Rails for .NET Developers</h4>
<p>Or perhaps you&#8217;re coming from a .NET background? This book has you covered!<br />
		&#8220;You&#8217;re already a .NET developer; we&#8217;ll help you get up and running as a Ruby on Rails developer on any operating system: Windows, Mac, or Linux. We start with a gentle introduction to the object-oriented Ruby language with examples and direct comparisons to C#, so you&#8217;ll quickly feel at home writing Ruby code for the first time.&#8221;</p>
<p><a href="http://www.pragprog.com/titles/cerailn/rails-for-net-developers">Read More</a></p>
</li>
<li>
<div><img width="165" border="0" src="http://nettuts.s3.amazonaws.com/417_ruby/images/rails-java.png" /></div>
<h4>Rails for Java Developers</h4>
<p>Or maybe you&#8217;re a hard-core Java developer seeking asylum with Rails?<br />
		&#8220;Written by experienced developers who love both Java and Ruby, this book will show you, via detailed comparisons and commentary, how to translate your hard-earned Java knowledge and skills into the world of Ruby and Rails.&#8221;</p>
<p><a href="http://www.pragprog.com/titles/fr_r4j/rails-for-java-developers">Read More</a></p>
</li>
<li>
<div><img width="165" border="0" src="http://nettuts.s3.amazonaws.com/417_ruby/images/advanced-rails.png" /></div>
<h4>Advanced Rails</h4>
<p>&#8220;This is the book for experienced Rails developers who want to go to the next level with this web development framework, with an in-depth look at techniques for dealing with databases, security, performance, web services and much more. Chapters in this book help you understand not only the tricks and techniques used within the Rails framework itself, but also how make use of ideas borrowed from other programming paradigms.&#8221;</p>
<p><a href="http://oreilly.com/catalog/9780596510329/">Read More</a></p>
</li>
<li>
<div><img width="165" border="0" src="http://nettuts.s3.amazonaws.com/417_ruby/images/rails-recipes.png" /></div>
<h4>Advanced Rails Recipes</h4>
<p>&#8220;With the help of a community of Rails chefs in the kitchen, here are 84 new ways to kick your Rails apps up a notch. Advanced Rails Recipes is a collection of practical recipes for spicing up your web application without a lot of prep and cleanup. You&#8217;ll learn how the pros have solved the tough problems using the most up-to-date Rails 2 techniques so you can deliver your stunning web app quicker and easier.&#8221;</p>
<p><a href="http://www.pragprog.com/titles/fr_arr/advanced-rails-recipes">Read More</a></p>
</li>
<li>
<div><img width="165" border="0" src="http://nettuts.s3.amazonaws.com/417_ruby/images/rspec.png" /></div>
<h4>The RSpec Book</h4>
<p>&#8220;RSpec, Ruby&#8217;s leading Behaviour Driven Development tool, helps you do TDD right by embracing the design and documentation aspects of TDD. It encourages readable, maintainable suites of code examples that not only test your code, they document it as well. The RSpec Book will teach you how to use RSpec, Cucumber, and other Ruby tools to develop truly agile software that gets you to market quickly and maintains its value as evolving market trends drive new requirements.&#8221;</p>
<p><a href="http://www.pragprog.com/titles/achbd/the-rspec-book">Read More</a></p>
</li>
<li>
<div><img width="165" border="0" src="http://nettuts.s3.amazonaws.com/417_ruby/images/simply-rails.png" /></div>
<h4>Simply Rails 2</h4>
<p>&#8220;Simply Rails 2 is an easy-to-follow, practical and fun guide to Ruby on Rails for beginners. It covers all you need to get up and running, from installing Ruby, Rails and SQLite to building and deploying a fully featured web application.&#8221;</p>
<p><a href="http://www.sitepoint.com/books/rails2/">Read More</a></p>
</li>
</ul>
<ul class="webroundup">
<li>Follow us on <a href="http://www.twitter.com/nettuts">Twitter</a>, or subscribe to the <a href="http://feeds.feedburner.com/nettuts" title="Nettuts+ RSS Feed">Nettuts+ RSS Feed</a> for more daily web development tuts and articles.</li>
</ul>
<p>
<script type="text/javascript"><!--digg_url = "post permalink (not digg url)"; // -->
</script><br />
<script src="http://digg.com/tools/diggthis.js" type="text/javascript"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://net.tutsplus.com/tutorials/ruby/your-ruby-library-essential-reading/feed/</wfw:commentRss>
		<slash:comments>36</slash:comments>
		</item>
		<item>
		<title>From CodeIgniter to Ruby on Rails: A Conversion</title>
		<link>http://net.tutsplus.com/tutorials/ruby/from-codeigniter-to-ruby-on-rails-a-conversion/</link>
		<comments>http://net.tutsplus.com/tutorials/ruby/from-codeigniter-to-ruby-on-rails-a-conversion/#comments</comments>
		<pubDate>Thu, 30 Jul 2009 16:59:39 +0000</pubDate>
		<dc:creator>Dan Harper</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[codeigniter]]></category>
		<category><![CDATA[ruby on rails]]></category>

		<guid isPermaLink="false">http://net.tutsplus.com/?p=6017</guid>
		<description><![CDATA[<img src="http://nettuts.s3.amazonaws.com/394_ciRuby/images/postimg.jpg" alt="CodeIgniter to Ruby on Rails: A Conversion" />]]></description>
			<content:encoded><![CDATA[<p>Today, we&#8217;ll be creating a <a href="http://net.tutsplus.com/tutorials/php/create-a-basic-shoutbox-with-php-and-sql/">simple shoutbox</a> using the CodeIgniter PHP framework. We&#8217;ll then port this exact application, piece-by-piece, to Ruby on Rails!</p>
<p><span id="more-6017"></span></p>
<div class="tutorial_image">
<a href="http://nettuts.s3.amazonaws.com/394_ciRuby/Source.zip"><img src="http://nettuts.com/wp-content/themes/nettuts/site_images/button_src_nm.jpg"></a><br />
<a href="http://nettuts.s3.amazonaws.com/394_ciRuby/Demo/index.html"><img src="http://nettuts.com/wp-content/themes/nettuts/site_images/button_demo_nm.jpg"></a>
</div>
<div class="tutorial_image">
<img src="http://nettuts.s3.amazonaws.com/394_ciRuby/images/errors.jpg" alt="Final Product" />
</div>
<p>Throughout this tutorial, we&#8217;ll create a simple shoutbox application in CodeIgniter, and then port it over to Ruby on Rails. We&#8217;ll be comparing the code between the two applications to see where they are similar, and where they differ. Learning Rails is much easier if you are already familiar with an MVC (Model, View, Controller) framework structure. </p>
<h3>Do I Need Previous CodeIgniter Experience?</h3>
<p> Yes, or experience in PHP and another MVC framework (CakePHP, Zend etc.). Check out some of the other <a href="http://net.tutsplus.com/?s=codeigniter">CI tutorials here on Nettuts</a>, including the <a href="http://net.tutsplus.com/videos/screencasts/codeigniter-from-scratch-day-1/">from scratch</a> video series!</p>
<h3>Do I Need Previous Ruby/Rails Experience?</h3>
<p> While it would help, no. I&#8217;ve done my best to make direct comparisons between Ruby and PHP, and between Rails and CodeIgniter, so by applying your existing knowledge it won&#8217;t be too hard.</p>
<h3>Hello, CodeIgniter</h3>
<p>Begin by downloading the CodeIgniter framework to your local/web server, and set up your database (I named it <code class="filename">ci_shoutbox</code>) with the following SQL commands:</p>
<pre name="code" class="sql">
CREATE TABLE `shouts` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `message` text NOT NULL,
  PRIMARY KEY (`id`)
);

INSERT INTO `shouts` (`id`,`name`,`email`,`message`)
VALUES
  (1,'Dan Harper','email@example.com','Hello, World!'),
  (2,'Bob','a@a.com','This looks great!'),
  (3,'Dan Harper','email@example.com','Hey, thanks for the comment!');
</pre>
<p>As usual in CodeIgniter, enter your details into <code class="filename">/system/application/config/database.php</code>:</p>
<pre name="code" class="php">
$db['default']['hostname'] = "localhost";
$db['default']['username'] = "root";
$db['default']['password'] = "";
$db['default']['database'] = "ci_shoutbox";
</pre>
<p>Then <code class="filename">config.php</code>:</p>
<pre name="code" class="php">
$config['base_url']	= "http://localhost/shoutbox/";
...
$config['global_xss_filtering'] = TRUE;
...
$config['rewrite_short_tags'] = TRUE;
</pre>
<p>And <code class="filename">autoload.php</code>:</p>
<pre name="code" class="php">
$autoload['libraries'] = array('database', 'form_validation', 'session');
$autoload['helper'] = array('url', 'form');
...
$autoload['model'] = array('shout');
</pre>
<p>Finally set the default controller inside <code class="filename">routes.php</code>:</p>
<pre name="code" class="php">
$route['default_controller'] = "shouts";
</pre>
<h4>Controller &amp; Model</h4>
<p>Since this is such a simple application, we only need one controller and one model. Inside <code class="filename">/controllers/</code> create <code class="filename">shouts.php</code>:</p>
<pre name="code" class="php">
&lt;?php
class Shouts extends Controller {

  function Shouts() {
    parent::Controller();
  }

}
</pre>
<p>And the model as <code class="filename">/models/shout.php</code>:</p>
<pre name="code" class="php">
&lt;?php
class Shout extends Model {

  function Shout() {
    parent::Model();
  }

}
</pre>
<h3>Retrieving the Shouts</h3>
<p>Our front page, the index, outputs the 10 latest shouts from the database. Start by adding the following to the Shouts controller:</p>
<pre name="code" class="php">
function index() {
  $data['shouts'] = $this->shout->all_shouts();
  $this->load->view('shouts/index.php', $data);
}
</pre>
<p>On line 2, we call the <code>all_shouts()</code> function from the Shout model.<br />
Following this, we load the relevant view file, and pass the <code>$data</code> variable along to it (CodeIgniter will automatically take apart the <code>$data</code> array, so that we can access the shouts simply as <code>$shouts</code> instead of <code>$data['shouts']</code>).</p>
<h4>Calling the Database</h4>
<p>Let&#8217;s create the <code>all_shouts()</code> function in our model now:</p>
<pre name="code" class="php">
function all_shouts() {
  $data = array();
  $this->db->order_by('id', 'DESC');
  $q = $this->db->get('shouts', 10);

  if ($q->num_rows() > 0) {
    foreach ($q->result() as $row) {
      $data[] = $row;
    }
  }

  return $data;
  $q->free_result();
}
</pre>
<p>This is relatively straight-forward. We retrieve the 10 most recent records from the &#8217;shouts&#8217; table, and output them in descending order. This will build the following SQL command behind-the-scenes:</p>
<pre name="code" class="sql">
SELECT * FROM `shouts` ORDER BY `id` DESC LIMIT 10;
</pre>
<p>If any records were found, they are added to the <code>$data</code> array and returned to the controller.</p>
<h4>The View</h4>
<p>Inside the <code class="filename">/views/</code> directory, create the following files and folders:</p>
<ul>
<li><code class="filename">footer.php</code></li>
<li><code class="filename">header.php</code></li>
<li><code class="filename">/shouts/</code>
<ul>
<li><code class="filename">index.php</code></li>
</ul>
</li>
</ul>
<p>Add the following to <code class="filename">/shouts/index.php</code>:</p>
<pre name="code" class="php">
&lt;?php
$this-&gt;load-&gt;view(&#x27;/header.php&#x27;);

if ($shouts) {
  echo &#x27;&lt;ul&gt;&#x27;;
  foreach ($shouts as $shout) {
    $gravatar = &#x27;http://www.gravatar.com/avatar.php?gravatar_id=&#x27; . md5(strtolower($shout-&gt;email)) . &#x27;&amp;size=70&#x27;;
    ?&gt;

    &lt;li&gt;
      &lt;div class=&quot;meta&quot;&gt;
        &lt;img src=&quot;&lt;?= $gravatar ?&gt;&quot; alt=&quot;Gravatar&quot; /&gt;
        &lt;p&gt;&lt;?= $shout-&gt;name ?&gt;&lt;/p&gt;
      &lt;/div&gt;
      &lt;div class=&quot;shout&quot;&gt;
        &lt;p&gt;&lt;?= $shout-&gt;message ?&gt;&lt;/p&gt;
      &lt;/div&gt;
    &lt;/li&gt;

    &lt;?php
  }
}
else {
  echo &#x27;&lt;p class=&quot;error&quot;&gt;No shouts found!&lt;/p&gt;&#x27;;
}

$this-&gt;load-&gt;view(&#x27;/footer.php&#x27;);
</pre>
<p>On line 2 we include <code class="filename">header.php</code>.<br />
If any shouts were returned from the database, we loop through them using <code>foreach</code> and create a basic list with the author&#8217;s Gravatar, their name and the message. If no shouts were found, we display an error message.<br />
Finally, we include the <code class="filename">footer.php</code>.</p>
<p>Note that on line 7, we build the <a href="http://gravatar.com">Gravatar</a> URL. The URL contains an MD5 hash of the user&#8217;s email address. We use PHP&#8217;s <code>strtolower()</code> function to ensure the email is all lower-case in case the Gravatar service is case-sensitive.</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/394_ciRuby/images/shouts.jpg" border="0" /></div>
<p>Continuing on, we need a form at the bottom of the page to add a new shout. Before we include the footer view file, add the following:</p>
<pre name="code" class="php">
echo form_open(&#x27;shouts/create&#x27;); ?&gt;
  &lt;h2&gt;Shout!&lt;/h2&gt;

  &lt;div class=&quot;fname&quot;&gt;
    &lt;label for=&quot;name&quot;&gt;&lt;p&gt;Name:&lt;/p&gt;&lt;/label&gt;
    &lt;input type=&quot;text&quot; name=&quot;name&quot; value=&quot;&lt;?= set_value(&#x27;name&#x27;) ?&gt;&quot; /&gt;
    &lt;/div&gt;

  &lt;div class=&quot;femail&quot;&gt;
    &lt;label for=&quot;email&quot;&gt;&lt;p&gt;Email:&lt;/p&gt;&lt;/label&gt;
    &lt;input type=&quot;text&quot; name=&quot;email&quot; value=&quot;&lt;?= set_value(&#x27;email&#x27;) ?&gt;&quot; /&gt;
  &lt;/div&gt;

  &lt;textarea name=&quot;message&quot; rows=&quot;5&quot; cols=&quot;40&quot;&gt;&lt;?= set_value(&#x27;message&#x27;) ?&gt;&lt;/textarea&gt;

  &lt;p&gt;&lt;input type=&quot;submit&quot; value=&quot;Submit&quot; /&gt;&lt;/p&gt;
  &lt;?php
echo form_close();
$this-&gt;load-&gt;view(&#x27;/footer.php&#x27;);
</pre>
<p>On line 1 we use the <code>form_open()</code> function from CodeIgniter&#8217;s Form helper. This generates a <code>&lt;form&gt;</code> opening tag with the relevant parameters, and will point to shouts/create (the Create function inside the Shouts controller).<br />
The rest is a normal HTML form, except we echo the <code>set_value()</code> function for each &#8216;value&#8217;. We will be adding validation to the form shortly and  this ensures that if there are any errors, the submitted data is automatically re-entered into the form.</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/394_ciRuby/images/form.jpg" border="0" /></div>
<p>Finally, we&#8217;ll need to create the header &amp; footer. Add the following to <code class="filename">/views/header.php</code>:</p>
<pre name="code" class="html">
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot;
&quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;

&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;
&lt;head&gt;
&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=utf-8&quot; /&gt;
&lt;title&gt;Shoutbox in CodeIgniter&lt;/title&gt;
&lt;link rel=&quot;stylesheet&quot; href=&quot;&lt;?php echo base_url(); ?&gt;css/style.css&quot; type=&quot;text/css&quot; /&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;div id=&quot;container&quot;&gt;

  &lt;h1&gt;Shoutbox&lt;/h1&gt;
  &lt;h5&gt;
    &lt;a href=&quot;http://www.danharper.me&quot; title=&quot;Dan Harper&quot;&gt;Dan Harper &lt;/a&gt; :
    &lt;a href=&quot;http://net.tutsplus.com&quot; title=&quot;Nettuts - Spoonfed Coding Skills&quot;&gt;Nettuts&lt;/a&gt;
  &lt;/h5&gt;

  &lt;div id=&quot;boxtop&quot;&gt;&lt;/div&gt;
  &lt;div id=&quot;content&quot;&gt;
</pre>
<p>See on line 8, when including the stylesheet, we use the <code>base_url()</code> function from CodeIgniter&#8217;s URL helper to generate the URL to the root of the site &ndash; this will put the stylesheet at http://example.com/css/style.css.</p>
<p>Add the following to <code class="filename">/views/footer.php</code>:</p>
<pre name="code" class="html">
  &lt;/div&gt;&lt;!--/content--&gt;
&lt;div id=&quot;boxbot&quot;&gt;&lt;/div&gt;
&lt;/div&gt;&lt;!--/container--&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<h3>Submission &amp; Validation</h3>
<p>Since the form directs to a Create function in the Shouts controller, let&#8217;s create that now:</p>
<pre name="code" class="php">
function create() {
  $data['shouts'] = $this->shout->all_shouts();

  $this->form_validation->set_rules('name', 'Name', 'required|max_length[255]|htmlspecialchars');
  $this->form_validation->set_rules('email', 'Email', 'valid_email|required|max_length[255]|htmlspecialchars');
  $this->form_validation->set_rules('message', 'Shout', 'required|htmlspecialchars');

  if ($this->form_validation->run() == FALSE) {
    $this->load->view('shouts/index.php', $data);
  }
  else {
    $this->shout->create();
    $this->session->set_flashdata('success', 'Thanks for shouting!');
    redirect('shouts/index');
  }
}
</pre>
<p>On line 2 we retrieve the shouts (as we did on the index function), as they still need to be shown.<br />
Lines 4-6 are our validation rules. We first pass the input&#8217;s &#8216;name&#8217; from the submitted form to check, followed by a &#8216;human-readable&#8217; version. The third parameter holds a pipe-separated (&#8217;|') list of validation rules.</p>
<p>For example, we set all the fields as &#8216;required&#8217; as well as run them through &#8216;htmlspecialchars&#8217; before submission. &#8216;Name&#8217; and &#8216;Email&#8217; have a max length set, and the submitted email field must resemble an email address.</p>
<p>If the validation fails, the index view is loaded again; otherwise we run the <code>create()</code> function from the Shout model. On line 13, we set a success message in the flash data which will be displayed on the next executed page.</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/394_ciRuby/images/errors.jpg" border="0" /></div>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/394_ciRuby/images/success.jpg" border="0" /></div>
<p>Before continuing, we must display the error and success messages (see images above) in our view. Add the following directly after we include the header in <code class="filename">/views/shouts/index.php</code>:</p>
<pre name="code" class="php">
if ($this-&gt;session-&gt;flashdata(&#x27;success&#x27;)) {
  echo &#x27;&lt;p class=&quot;success&quot;&gt;&#x27; . $this-&gt;session-&gt;flashdata(&#x27;success&#x27;) . &#x27;&lt;/p&gt;&#x27;;
}

echo validation_errors(&#x27;&lt;p class=&quot;error&quot;&gt;&#x27;, &#x27;&lt;/p&gt;&#x27;);
</pre>
<h4>Insert Into Database</h4>
<p>Inside the Shout model, enter the following:</p>
<pre name="code" class="php">
function create() {
  $data = array(
    'name'    =>  $this->form_validation->set_value('name'),
    'email'   =>  $this->form_validation->set_value('email'),
    'message' =>  $this->form_validation->set_value('message')
  );
  $this->db->insert('shouts', $data);
}
</pre>
<p>Very simple, we compile an array containing the submitted data, and insert it into the `shouts` table.</p>
<h4>Styling</h4>
<p>In the very root directory for your application &ndash; in the same directory as CodeIgniter&#8217;s <code class="filename">/system/</code> folder, create two new folders: <code class="filename">/css/</code> and <code class="filename">/images/</code>.<br />
In the CSS folder, add the following to a file named <code class="filename">style.css</code>:</p>
<pre name="code" class="css">
* {
margin: 0;
padding: 0;
}

body {
background: #323f66 top center url("../images/back.png") no-repeat;
color: #ffffff;
font-family: Helvetica, Arial, Verdana, sans-serif;
}

h1 {
font-size: 3.5em;
letter-spacing: -1px;
background: url("../images/shoutbox.png") no-repeat;
width: 303px;
height: 66px;
margin: 0 auto;
text-indent: -9999em;
color: #33ccff;
}

h2 {
font-size: 2em;
letter-spacing: -1px;
background: url("../images/shout.png") no-repeat;
width: 119px;
height: 44px;
text-indent: -9999em;
color: #33ccff;
clear: both;
margin: 15px 0;
}

h5 a:link, h5 a:visited {
color: #ffffff;
text-decoration: none;
}

h5 a:hover, h5 a:active, h5 a:focus {
border-bottom: 1px solid #fff;
}

p {
font-size: 0.9em;
line-height: 1.3em;
font-family: Lucida Sans Unicode, Helvetica, Arial, Verdana, sans-serif;
}

p.error, .errorExplanation li {
background-color: #603131;
border: 1px solid #5c2d2d;
padding: 10px !important;
margin-bottom: 15px;
}

p.success {
background-color: #313d60;
border: 1px solid #2d395c;
padding: 10px;
margin-bottom: 15px;
}

#container {
width: 664px;
margin: 20px auto;
text-align: center;
}

#boxtop {
margin: 30px auto 0px;
background: url("../images/top.png") no-repeat;
width: 663px;
height: 23px;
}

#boxbot {
margin: 0px auto 30px;
background: url("../images/bot.png") no-repeat;
width: 664px;
height: 25px;
}

#content {
margin: 0 auto;
width: 600px;
text-align: left;
background: url("../images/bg.png") repeat-y;
padding: 15px 35px;
overflow: hidden;
}

#content ul {
margin-left: 0;
margin-bottom: 15px;
}

#content ul li {
list-style: none;
clear: both;
padding-top: 30px;
}

#content ul li:first-child {
padding-top:0;
}

.meta {
width: 85px;
text-align: left;
float: left;
min-height: 110px;
font-weight: bold;
}

.meta img {
padding: 5px;
background-color: #313d60;
}

.meta p {
font-size: 0.8em;
}

.shout {
width: 500px;
float: left;
margin-left: 15px;
min-height: 110px;
padding-top: 5px;
}

form {
clear: both;
margin-top: 135px !important;
}

.fname, .femail {
width: 222px;
float: left;
}

form p {
font-weight: bold;
margin-bottom: 3px;
}

form textarea {
width: 365px;
overflow: hidden;
}

form input, form textarea {
background-color: #313d60;
border: 1px solid #2d395c;
color: #ffffff;
padding: 5px;
font-family: Lucida Sans Unicode, Helvetica, Arial, Verdana, sans-serif;
margin-bottom: 10px;
}
</pre>
<p>And save the following images into the <code class="filename">/images/</code> folder: (the images will be the correct size when saved!)</p>
<div class="tutorial_image">back.png<br /><img src="http://nettuts.s3.amazonaws.com/394_ciRuby/images/back.png" width="600" height="30" border="0" /></div>
<div class="tutorial_image">bg.png<br /><img src="http://nettuts.s3.amazonaws.com/394_ciRuby/images/bg.png" width="600" height="30" border="0" /></div>
<div class="tutorial_image">bot.png<br /><img src="http://nettuts.s3.amazonaws.com/394_ciRuby/images/bot.png" width="600" height="30" border="0" /></div>
<div class="tutorial_image">shout.png<br /><img src="http://nettuts.s3.amazonaws.com/394_ciRuby/images/shout.png" border="0" /></div>
<div class="tutorial_image">shoutbox.png<br /><img src="http://nettuts.s3.amazonaws.com/394_ciRuby/images/shoutbox.png" border="0" /></div>
<div class="tutorial_image">top.png<br /><img src="http://nettuts.s3.amazonaws.com/394_ciRuby/images/top.png" width="600" height="30" border="0" /></div>
<p>To confirm, your directory structure should look like the image below:</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/394_ciRuby/images/filelayout.png" border="0" /></div>
<p><strong>And&#8230; done!</strong> If you think we wrote very little actual back-end code in CI, wait until we get to Rails where all database interaction is automated!</p>
<p>&nbsp;</p>
<h3>Hello, Rails</h3>
<p>For this tutorial, I assume you already have Ruby, Rails and MySQL (or your preferred database engine) installed correctly on your system. If not, see the <a href="http://rubyonrails.org/download">Rails installation guide</a> and <a href="http://dev.mysql.com/downloads/mysql/5.1.html#downloads">MySQL download page</a>. If you happen to be running Mac OSX Leopard, Ruby and Rails both come pre-installed.</p>
<p>It&#8217;s also useful to know how to navigate in your operating system using the command line. For example to change directory, use <code>cd foldername</code>, or <code>cd C:\Users\Dan</code> etc.</p>
<p>Rails provides a number of command-line tools to speed up development of your application. Inside the Terminal (or Command Prompt in Windows), navigate to the folder you wish to store your Rails projects in. Personally I store them in a <code class="filename">/rails/</code> directory in my User area.</p>
<h4>The Set Up</h4>
<p>Run the following to dump a copy of Rails for your application:</p>
<pre name="code" class="ruby">
rails -d mysql shoutbox
</pre>
<p>Here, Rails will install into a <code class="filename">/shoutbox/</code> directory. As MySQL is my preferred database engine, I specify <code>-d mysql</code>. If you prefer to use MySQLlite (the default in Rails), you would simply run <code>rails shoutbox</code>.<br />
Navigate into the shoutbox directory:</p>
<pre name="code" class="ruby">
cd shoutbox
</pre>
<p>Now, we&#8217;ll generate the Controller and Model:</p>
<pre name="code" class="ruby">
ruby script/generate controller Shouts

ruby script/generate model Shout
</pre>
<p>Rails has now generated our &#8216;Shouts&#8217; controller and &#8216;Shout&#8217; model. It&#8217;s important to know that Rails encourages a strict naming style.<br />
Your controller should be named the plural of whatever it will deal with (eg. Shouts, Users, Listings). A controller typically will only deal with one model, which is named in the singular (eg. Shout, User, Listing). Following this standard will ensure Rails can use all it&#8217;s functionality.</p>
<p>Inside your shoutbox directory, open the <code class="filename">/config/database.yml</code> file, this stores our database details. Enter your details under the &#8216;development&#8217; section:</p>
<pre name="code" class="ruby">
development:
  adapter: mysql
  encoding: utf8
  reconnect: false
  database: shoutbox_development
  pool: 5
  username: root
  password:
  socket: /tmp/mysql.sock
</pre>
<p>You can see Rails has automatically set the configuration file to be using the MySQL adapter. You will likely only need to alter the username and password.<br />
Don&#8217;t worry, you should not have created the <code class="filename">shoutbox_development</code> database yet. We&#8217;ll create that next.</p>
<p>Next, open the <code class="filename">/db/migrate/***_create_shouts.rb</code> file (most versions of Rails will prefix the file name with the date and time):</p>
<pre name="code" class="ruby">
class CreateShouts &lt; ActiveRecord::Migration
  def self.up
    create_table :shouts do |t|

      t.timestamps
    end
  end

  def self.down
    drop_table :shouts
  end
end
</pre>
<p>This is a database migration file. Rails use these to help developers keep their databases structured correctly since they can become messy when several developers are altering database tables at the same time.<br />
You will also be able to roll your database back to a previous version if you need to.</p>
<p>In here, we will add our database fields:</p>
<pre name="code" class="ruby">
class CreateShouts &lt; ActiveRecord::Migration
  def self.up
    create_table :shouts do |t|
      t.string :name
      t.string :email
      t.text :message
      t.timestamps
    end
  end

  def self.down
    drop_table :shouts
  end
end
</pre>
<p>This may look scary, but it&#8217;s very simple! <code>t.string :name</code> creates a &#8216;name&#8217; field in the database, which will be stored as a string (ie. &#8216;varchar&#8217;). The same goes for the &#8216;email&#8217; field.<br />
A &#8216;message&#8217; field is added and stored as text (as it is in SQL).</p>
<p>You will notice Rails automatically included <code>t.timestamps</code>. This includes &#8216;created_at&#8217; and &#8216;updated_at&#8217; fields which Rails will automatically fill in when a field is created or updated.<br />
Also, Rails will automatically create an &#8216;id&#8217; field, so we don&#8217;t need to define that ourselves.</p>
<p>This is equivalent to the following SQL command:</p>
<pre name="code" class="sql">
CREATE TABLE `shouts` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  `message` text,
  `ipaddress` varchar(15) DEFAULT NULL,
  `created_at` datetime DEFAULT NULL,
  `updated_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
);
</pre>
<p>While it can take a little getting-used-to when creating these migrations, they&#8217;re much easier to type than SQL!</p>
<p>Finally, run the following two commands in the Terminal to create and set up the database:</p>
<pre name="code" class="ruby">
rake db:create

rake db:migrate
</pre>
<p>The first command creates the database, named &#8217;shoutbox_development&#8217;. The second runs any out-standing database migrations (in this case, our <code class="filename">***_create_shouts.rb</code> file).</p>
<p>Start the server with and then visit <a href="http://localhost:3000">http://localhost:3000</a> (or whatever port the server says it is running on &ndash; in most cases it&#8217;s 3000):</p>
<pre name="code" class="ruby">
ruby script/server
</pre>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/394_ciRuby/images/rails-welcome.png" border="0" /></div>
<p>To remove the default welcome page, first remove the file at <code class="filename">/public/index.html</code>, then inside <code class="filename">/config/routes.rb</code>, insert the following anywhere between the first and last lines:</p>
<pre name="code" class="ruby">
map.root :controller => "shouts"
</pre>
<p>You will need to restart the server whenever you make alterations to the controller or to the routes &ndash; press Ctrl+C, then re-run <code>ruby script/server</code>.</p>
<p>That concludes the configuration process for Rails. While this whole process may seem complicated right now, you can do it in just a few minutes, and once you get used to it, it&#8217;s much quicker than setting up a CodeIgniter project.</p>
<h4>Dummy Data</h4>
<p>Before display the shouts, we&#8217;ll need some data in the database to display. You could create these entries through your preferred database management program, however we&#8217;re going to use a great Rails feature instead &ndash; the interactive console.</p>
<p>From your application folder in the Terminal, run <code>ruby script/console</code>. This is an interactive Ruby interpreter, which is also hooked up to our Rails application, so we can interact with it!</p>
<p>One very important thing to remember with regard to Rails, is that your model is <strong>automatically linked with the corresponding database table</strong>. For example, your &#8216;Shout&#8217; model is linked with the &#8217;shouts&#8217; table in your database &ndash; this is a key reason why following Rails&#8217; naming conventions can be very useful!</p>
<p>Run the following ruby code inside the interactive console:</p>
<pre name="code" class="ruby">
shout = Shout.new(
  :name => 'Dan Harper',
  :email => 'email@example.com',
  :message => 'Hello, World!')
</pre>
<p>Here, we invoke Rails&#8217; <code>new</code> method on the &#8216;Shout&#8217; model &ndash; this will create a new record in the shouts database table. We also pass a hash containing the data we want to enter.<br />
This is stored in the &#8217;shout&#8217; variable.</p>
<p><strong>Note:</strong> A &#8216;hash&#8217; is what PHP calls an associate array &ndash; an array where you can also set your own key.<br />
A rough PHP equivalent of this code would be:</p>
<pre name="code" class="php">
$shout = $this->shout->new(
  'name' => 'Dan Harper',
  'email' => 'email@example.com',
  'message' => 'Hello, World!');
</pre>
<p>Finally, save this into the database with:</p>
<pre name="code" class="ruby">
shout.save
</pre>
<p>If you entered the code correctly, ruby should return &#8216;true&#8217;.<br />
You can now retrieve this from the database with:</p>
<pre name="code" class="ruby">
shout = Shout.find :last

shout.name
</pre>
<p>The first command will find the most recent row in the shouts table and store it in the &#8217;shout&#8217; variable. We can find look at a specific item with <code>shout.name</code> which should return whatever you entered as the &#8216;name&#8217; for the record.</p>
<p>Repeat the <code>Shout.new</code> and <code>Shout.save</code> process a few more times to add more records to the database.</p>
<h3>Displaying Shouts</h3>
<p>Inside the <code class="filename">/app/controllers/shouts_controller.rb</code> file, enter the following between the existing class statement:</p>
<pre name="code" class="ruby">
def index
  @shouts = Shout.all_shouts
end
</pre>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/394_ciRuby/images/rails-controller.png" border="0" /></div>
<p>We call the <code>all_shouts</code> method from the &#8216;Shout&#8217; model, and store the result inside the <code>shouts</code> instance variable (as seen by the <code>@</code>).</p>
<p>In CodeIgniter, the equivalent code was:</p>
<pre name="code" class="php">
class Shouts extends Controller {

  function Shouts() {
    parent::Controller();
  }

  function index() {
    $data['shouts'] = $this->shout->all_shouts();
    $this->load->view('shouts/index.php');
  }

}
</pre>
<p>Some noticeable differences are:</p>
<ol>
<li>Rails uses the &#8216;&lt;&#8217; symbol in place of &#8216;extends&#8217; when creating a class;</li>
<li>To create a function/method we use <code>def</code> instead of <code>function</code>;</li>
<li>Rails doesn&#8217;t require a constructor method;</li>
<li>Rails automatically loads the view file for the current method. In this case, the view file is located at <code class="filename">/app/views/shouts/index.html.erb</code>;</li>
<li>It is already noticeable that code is much cleaner in Rails. You don&#8217;t need parenthesis (brackets) when defining a funcion/method if it doesn&#8217;t contain any parameters, we don&#8217;t need to add a semi-colon at the end of each statement and there are no curly brackets in sight!</li>
</ol>
<h4>The Model</h4>
<p>Inside <code class="filename">/app/models/shout.rb</code> enter the following inside the class to define the <code>all_shouts</code> function:</p>
<pre name="code" class="ruby">
def self.all_shouts
  Shout.find(:all, :limit => 10, <img src='http://net.tutsplus.com/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> rder => 'id DESC')
end
</pre>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/394_ciRuby/images/rails-model.png" border="0" /></div>
<p>Here, we run Rails&#8217; <code>find</code> on the Shout model (ie. the shouts table). We pass a hash telling the method to limit the number of results to 10 in descending order.<br />
This is the equivalent CodeIgniter code:</p>
<pre name="code" class="php">
function all_shouts() {
  $data = array();
  $this->db->order_by('id', 'DESC');
  $q = $this->db->get('shouts', 10);

  if ($q->num_rows() > 0) {
    foreach ($q->result() as $row) {
      $data[] = $row;
    }
  }

  return $data;
  $q->free_result();
}
</pre>
<p>Yeah&hellip; so much simpler!<br />
Also note that in Ruby, if you don&#8217;t specifically <code>return</code> something, the last statement is automatically returned. For example, we could have used the following instead (although it would make no difference):</p>
<pre name="code" class="ruby">
def self.all_shouts
  return Shout.find(:all, :limit => 10, <img src='http://net.tutsplus.com/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> rder => 'id DESC')
end
</pre>
<h4>The View</h4>
<p>In CodeIgniter, we had to manually include header &amp; footer files in each view. Rails takes a slightly different approach. Inside <code class="filename">/views/layouts/</code> create a file named <code class="filename">application.html.erb</code> with the following inside:</p>
<pre name="code" class="html">
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot;
&quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;
&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;
&lt;head&gt;
&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=utf-8&quot; /&gt;
&lt;title&gt;Shoutbox in Ruby on Rails&lt;/title&gt;
&lt;%= stylesheet_link_tag &#x27;style&#x27;, :media =&gt; &#x27;screen&#x27; %&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;div id=&quot;container&quot;&gt;

  &lt;h1&gt;Shoutbox&lt;/h1&gt;
  &lt;h5&gt;
    &lt;a href=&quot;http://www.danharper.me&quot; title=&quot;Web Developer&quot;&gt;Dan Harper &lt;/a&gt; :
    &lt;a href=&quot;http://net.tutsplus.com&quot; title=&quot;Nettuts - Spoonfed Coding Skills&quot;&gt;Nettuts&lt;/a&gt;
  &lt;/h5&gt;

  &lt;div id=&quot;boxtop&quot;&gt;&lt;/div&gt;
  &lt;div id=&quot;content&quot;&gt;

    &lt;%= yield %&gt;

  &lt;/div&gt;&lt;!--/content--&gt;
&lt;div id=&quot;boxbot&quot;&gt;&lt;/div&gt;
&lt;/div&gt;&lt;!--/container--&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>This is predominantly a normal HTML layout, combining both our header and footer. On line 7 we include a link to a stylesheet. Rails provides a <code class="filename">/public/</code> folder in which you include images, stylesheet, javascript files and any static HTML files. In this case, the code will output a link to a stylesheet at <code class="filename">/public/stylesheets/style.css</code>.</p>
<p>Further down, on line 21 is <code>&lt;%= yield %&gt;</code>. This will insert the main view file for the specific page in this place.</p>
<p><strong>Why .html.erb?</strong> All view files in Rails first have the extension for the specific format you want to output as, followed by .erb so the server will interpret the Ruby code inside it.<br />
This means you could also have a .xml.erb file if you want to export in XML for certain pages, etc.</p>
<p><code style="background:none;"><strong>&lt;%=  %&gt;</strong></code> Ruby uses <code>&lt;%</code> and <code>%&gt;</code> to wrap any Ruby code to be interpreted, in the same way PHP uses <code>&lt;?php</code> and <code>?&gt;</code>.<br />
On HTML pages, we use <code>&lt;%= ... %&gt;</code> (note the equals) to &#8216;print&#8217; code. In PHP we use either <code>&lt;?php echo ... ?&gt;</code> or <code>&lt;?= ... ?&gt;</code> to &#8216;echo&#8217; code.</p>
<p>Inside <code class="filename">/public/stylesheets/</code> create a file named <code class="filename">style.css</code> containing the same CSS we used in the CodeIgniter section.<br />
Also, paste the images from the CodeIgniter section into <code class="filename">/public/images/</code>.</p>
<p>If you restart the server now, and reload your browser, you should see a &#8216;Template is missing&#8217; error page. This is because we haven&#8217;t yet created the actual view for the current page.</p>
<p>The &#8216;Template is missing&#8217; error page tells us what file it was expecting:<br />
&#8220;Missing template <code class="filename">shouts/index.html.erb</code> in view path <code class="filename">app/views</code>&#8221;<br />
So let&#8217;s create that file now, and enter the following to test it out:</p>
<pre name="code" class="html">
Hello, World!
</pre>
<p>Reload the page, and you should be greeted with the following (if not, check you have the stylesheet &amp; images in the correct locations):</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/394_ciRuby/images/itworks.png" border="0" /></div>
<h4>Looping</h4>
<p>You will remember that in CodeIgniter, we used the code below to loop through and display each retrieved shout:</p>
<pre name="code" class="php">
&lt;?php
echo &#x27;&lt;ul&gt;&#x27;;
foreach ($shouts as $shout) {
  $gravatar = &#x27;http://www.gravatar.com/avatar.php?gravatar_id=&#x27; . md5(strtolower($shout-&gt;email)) . &#x27;&amp;size=70&#x27;;
  ?&gt;

  &lt;li&gt;
    &lt;div class=&quot;meta&quot;&gt;
      &lt;img src=&quot;&lt;?= $gravatar ?&gt;&quot; alt=&quot;Gravatar&quot; /&gt;
      &lt;p&gt;&lt;?= $shout-&gt;name ?&gt;&lt;/p&gt;
    &lt;/div&gt;
    &lt;div class=&quot;shout&quot;&gt;
      &lt;p&gt;&lt;?= $shout-&gt;message ?&gt;&lt;/p&gt;
    &lt;/div&gt;
  &lt;/li&gt;

  &lt;?php
}
echo &#x27;&lt;/ul&gt;&#x27;;
</pre>
<p>The equivalent in Ruby is the following (replace the &#8216;Hello, World!&#8217; message with this):</p>
<pre name="code" class="ruby">
&lt;ul&gt;
&lt;% for shout in @shouts

  gravatar = &#x27;http://www.gravatar.com/avatar.php?gravatar_id=&#x27; + Digest::MD5.hexdigest(h(shout.email.downcase)) + &#x27;&amp;size=70&#x27; %&gt;

  &lt;li&gt;
    &lt;div class=&quot;meta&quot;&gt;
      &lt;img src=&quot;&lt;%= gravatar %&gt;&quot; alt=&quot;Gravatar&quot; /&gt;
      &lt;p&gt;&lt;%= shout.name %&gt;&lt;/p&gt;
    &lt;/div&gt;
    &lt;div class=&quot;shout&quot;&gt;
      &lt;p&gt;&lt;%= shout.message %&gt;&lt;/p&gt;
    &lt;/div&gt;
  &lt;/li&gt;

&lt;% end %&gt;
&lt;/ul&gt;
</pre>
<p>On line 2 is a normal &#8216;foreach&#8217;-style loop in Ruby. Instead of the <code>foreach ($shouts as $shout)</code> in PHP, we use <code>for shout in @shouts</code> in Ruby.</p>
<p>The loop closes at <code>end</code> on line 16.</p>
<p>On line 4 we build the Gravatar URL in almost the same way as in PHP, with a few exceptions:</p>
<ol>
<li>In PHP, we use the dot character (.) to concatenate statements, Ruby uses the plus character (+), just like in JavaScript;<br />
	&nbsp;</li>
<li>Ruby&#8217;s version of PHP&#8217;s <code>md5()</code> function is <code>Digest::MD5.hexdigest()</code>;<br />
	&nbsp;</li>
<li>The <code>h()</code> function in Ruby is equivalent to PHP&#8217;s <code>htmlspecialchars()</code>;<br />
	&nbsp;</li>
<li>PHP uses <code>-></code> to access an object (eg. <code>$shout->email</code>). Ruby uses a dot, (eg. <code>shout.email</code>);<br />
	&nbsp;</li>
<li>To ensure the email address is in lower-case, we use <code>strtolower($shout->email)</code> in PHP. In Ruby, everything is an object and so we simply add <code>.downcase</code> to the end of a string or variable &ndash; <code>shout.email.downcase</code>. You could also <code>.upcase</code>, <code>.reverse</code>, etc.</li>
</ol>
<p>Refresh the page in your browser, and you should now see the shoutbox messages!</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/394_ciRuby/images/shouts.jpg" border="0" /></div>
<h4>Submission Form</h4>
<p>Continuing on, we need to include the form at the bottom of the page for submitting new shouts. First, take a look at the following line:</p>
<pre name="code" class="ruby">
&lt;% form_for :shout, :url =&gt; { :action =&gt; &#x27;create&#x27; } do |f| %&gt;
  ... code here ...
&lt;% end %&gt;
</pre>
<p>This is a block from Rails&#8217; form helper to easily create forms. <code>form_for :shout</code> links the form directly with the Shout model.</p>
<p><code>:url = { :action = 'create ' }</code> is a hash detailing where the form will direct to when submitted. In this case, the form will go to /shouts/create/ (Shouts controller, Create method). We could have typed: <code>:url = { :controller = 'shouts', :action = 'create }</code>, however the lack of a &#8216;controller&#8217; key in the hash tells Rails to use the current controller.</p>
<p>Finally, <code>do |f|</code> stores everything before in an <code>f</code> variable. For example, we could create a textbox linked to this using <code>f.text_field</code></p>
<p>Now we&#8217;ve explained that, enter this full form code at the bottom of your index view file:</p>
<pre name="code" class="ruby">
&lt;% form_for :shout, :url =&gt; { :action =&gt; &#x27;create&#x27; } do |f| %&gt;

  &lt;h2&gt;Shout!&lt;/h2&gt;

  &lt;div class=&quot;fname&quot;&gt;
    &lt;label for=&quot;name&quot;&gt;&lt;p&gt;Name:&lt;/p&gt;&lt;/label&gt;
    &lt;%= f.text_field :name, :size =&gt; 20 %&gt;
  &lt;/div&gt;

  &lt;div class=&quot;femail&quot;&gt;
    &lt;label for=&quot;email&quot;&gt;&lt;p&gt;Email:&lt;/p&gt;&lt;/label&gt;
    &lt;%= f.text_field :email, :size =&gt; 20 %&gt;
  &lt;/div&gt;

  &lt;%= f.text_area :message, :rows =&gt; 5, :cols =&gt; 40 %&gt;

  &lt;p&gt;&lt;%= submit_tag &#x27;Submit&#x27; %&gt;&lt;/p&gt;

&lt;% end %&gt;
</pre>
<p>And compare it with the CodeIgniter PHP version:</p>
<pre name="code" class="php">
echo form_open(&#x27;shouts/create&#x27;); ?&gt;
  &lt;h2&gt;Shout!&lt;/h2&gt;

  &lt;div class=&quot;fname&quot;&gt;
    &lt;label for=&quot;name&quot;&gt;&lt;p&gt;Name:&lt;/p&gt;&lt;/label&gt;
    &lt;input type=&quot;text&quot; name=&quot;name&quot; value=&quot;&lt;?= set_value(&#x27;name&#x27;) ?&gt;&quot; /&gt;
  &lt;/div&gt;

  &lt;div class=&quot;femail&quot;&gt;
    &lt;label for=&quot;email&quot;&gt;&lt;p&gt;Email:&lt;/p&gt;&lt;/label&gt;
    &lt;input type=&quot;text&quot; name=&quot;email&quot; value=&quot;&lt;?= set_value(&#x27;email&#x27;) ?&gt;&quot; /&gt;
  &lt;/div&gt;

  &lt;textarea name=&quot;message&quot; rows=&quot;5&quot; cols=&quot;40&quot;&gt;&lt;?= set_value(&#x27;message&#x27;) ?&gt;&lt;/textarea&gt;

  &lt;p&gt;&lt;input type=&quot;submit&quot; value=&quot;Submit&quot; /&gt;&lt;/p&gt;
  &lt;?php
echo form_close();
</pre>
<p>We make more use of Rails&#8217; form helper when creating the input fields, textarea and submit button. With <code>f.text_field :name, :size = 20</code> we are creating a textbox named &#8216;name&#8217; (matching the column in our database this should insert into). This would output in HTML as:</p>
<pre name="code" class="html">
&lt;input type=&quot;text&quot; name=&quot;shout[name]&quot; id=&quot;shout_name&quot; size=&quot;20&quot; /&gt;
</pre>
<p>In the CodeIgniter version of the app, we set each input&#8217;s &#8216;value&#8217; field to <code>&lt;?= set_value(&#x27;email&#x27;) ?&gt;</code> so CodeIgniter will automatically re-populate the fields if they fail the validation tests.<br />
In Rails, this is handled automatically since we are using Rails&#8217; form helper to create the inputs.</p>
<p>Refresh the page in your browser, and you should see the form at the bottom:</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/394_ciRuby/images/form.jpg" border="0" /></div>
<h3>Submission &amp; Validation</h3>
<p>The next step is to insert any submitted data into the database. The form directs to shouts/create, so let&#8217;s create the create action now (inside the Controller):</p>
<pre name="code" class="ruby">
def create
  @shouts = Shout.all_shouts

  @shout = Shout.new(params[:shout])
  if @shout.save
    flash[:notice] = 'Thanks for shouting!'
    redirect_to :action => 'index'
  else
    render :action => 'index'
  end
end
</pre>
<p>On line 2, we retrieve all our current shouts from the database since they still need to be displayed.</p>
<p>At line 4 we load Rails&#8217; <code>new</code> function on our Shout model. You will remember we used <code>Shout.new</code> when inserting dummy data into the database via the interactive console.<br />
We pass <code>new</code> our submitted data with <code>params[]</code> &ndash; this is how Rails accesses POST data.<br />
This is loaded into the <code>@shout</code> instance variable.</p>
<p>When we used the interactive console, we used <code>shout.save</code> to save the data. If it was successful, it returns &#8216;true&#8217;, otherwise &#8216;false&#8217; is returned. So on line 5 we check whether the shout can be saved into the database, if so, we load a success notice in the session&#8217;s &#8216;flashdata&#8217;, and redirect back to the index.<br />
Otherwise, we load index&#8217;s view file through the <code>render</code> function.</p>
<h4>Validation</h4>
<p>You may be wondering where our validation is handled, since we did this in the controller in CodeIgniter. In Rails, we place the rules inside the Model.<br />
When Rails attempts to insert data to the database (eg. with <code>@shout.save</code>), the Model will automatically check the data against our rules before attempting to save it. Thus, if validation fails, then <code>@shout.save</code> will return &#8216;false&#8217;, the view will be re-loaded and the error messages will display.</p>
<p>Inside the Shout model, insert the following before we define <code>self.all_shouts</code>:</p>
<pre name="code" class="ruby">
validates_presence_of :message
validates_length_of   :name,  :within => 1..255
validates_format_of   :email, :with   => /^[a-z0-9_.-]+@[a-z0-9-]+\.[a-z.]+$/i
</pre>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/394_ciRuby/images/validation.png" border="0" /></div>
<p>In true Ruby style, the validation rules read pretty much like natural English. On line 1 we ensure a &#8216;message&#8217; exists.</p>
<p>Next we check the length of the &#8216;name&#8217; field &ndash; it must be between 1 and 255 characters in length. <code>1..255</code> defines a range. We could define a range of between 10 and 15 with <code>10..15</code>, for example.</p>
<p>Finally, we check the submitted email is in the format of an email address using a regular expression. Basically, the submitted email must contain five parts:</p>
<ol>
<li>A string containing a combination of letters, numbers, an underscore, full-stop or hyphen;</li>
<li>The @ symbol;</li>
<li>A string containing a combination of letters, numbers or a hyphen;</li>
<li>A dot;</li>
<li>A string containing a combination of letters or a hyphen.</li>
</ol>
<h4>And finally&#8230;</h4>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/394_ciRuby/images/errors.jpg" border="0" /></div>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/394_ciRuby/images/success.jpg" border="0" /></div>
<p>We now just need to display the error/success messages in the view (see above). Add the following at the top of the index view file:</p>
<pre name="code" class="ruby">
&lt;%= error_messages_for :shout, :header_message =&gt; nil, :message =&gt; nil %&gt;
&lt;%= &#x27;&lt;p class=&quot;success&quot;&gt;&#x27; + flash[:notice] + &#x27;&lt;/p&gt;&#x27; if flash[:notice] %&gt;
</pre>
<p>On the first line we render any error messages for the shout form. We set <code>:header_message</code> and <code>:message</code> to <code>nil</code> (Ruby uses &#8216;nil&#8217;, PHP uses &#8216;null&#8217;) to stop the function displaying the normal messages it displays (we just want the error messages).</p>
<p>The second line displays our flash&#8217;ed success message. Note the <code>if flash[:notice]</code> at the end of the line. This ensures everything before it will attempt to display if the flash notice exists.<br />
Obviously, we could also have done the following instead; however it would have had the same effect:</p>
<pre name="code" class="ruby">
&lt;% if flash[:notice] %&gt;
  &lt;%= &#x27;&lt;p class=&quot;success&quot;&gt;&#x27; + flash[:notice] + &#x27;&lt;/p&gt;&#x27; %&gt;
&lt;% end %&gt;
</pre>
<h3>That&#8217;s It!</h3>
<p>Go try it out, it should function exactly as the CodeIgniter version yet in quite a bit less code (which is also much easier to read!)</p>
<p><strong>CodeIgniter:</strong><br />
Controller: <em>31 lines</em><br />
Model: <em>33 lines</em><br />
View: <em>69 lines</em><br />
Total: <strong>133 lines</strong></p>
<p><strong>Ruby on Rails:</strong><br />
Controller: <em>19 lines</em><br />
Model: <em>11 lines</em><br />
View: <em>64 lines</em><br />
Total: <strong>94 lines</strong></p>
<p>While this tutorial may have made the process of developing a Rails application long-winded, take a look back through your code and see how simple it all is!</p>
<p>If this tutorial has sparked your interest in Ruby and Ruby on Rails, I strongly recommend picking up a copy of <a href="http://www.pragprog.com/titles/ndphpr/rails-for-php-developers">Rails for PHP Developers</a>, <a href="http://www.pragprog.com/titles/rails3/agile-web-development-with-rails-third-edition">Agile Web Development with Rails</a> and/or <a href="http://www.pragprog.com/titles/ruby3/programming-ruby-1-9">Programming Ruby</a> from the Pragmatic Programmers.</p>
<p>Now go! Go explore the world of Rails!</p>
<ul class="webroundup">
<li>Follow us on <a href="http://www.twitter.com/nettuts">Twitter</a>, or subscribe to the <a href="http://feeds.feedburner.com/nettuts" title="NETTUTS RSS Feed">NETTUTS RSS Feed</a> for more daily web development tuts and articles.</li>
</ul>
<p>
<script type="text/javascript"><!--digg_url = "post permalink (not digg url)"; // -->
</script><br />
<script src="http://digg.com/tools/diggthis.js" type="text/javascript"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://net.tutsplus.com/tutorials/ruby/from-codeigniter-to-ruby-on-rails-a-conversion/feed/</wfw:commentRss>
		<slash:comments>67</slash:comments>
		</item>
		<item>
		<title>20 Ruby on Rails Tuts to Rule Them All</title>
		<link>http://net.tutsplus.com/tutorials/ruby/20-ruby-on-rails-tutorials-to-rule-them-all/</link>
		<comments>http://net.tutsplus.com/tutorials/ruby/20-ruby-on-rails-tutorials-to-rule-them-all/#comments</comments>
		<pubDate>Thu, 23 Jul 2009 15:24:00 +0000</pubDate>
		<dc:creator>Glen Stansberry</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[ruby and rails]]></category>
		<category><![CDATA[ruby on rails]]></category>

		<guid isPermaLink="false">http://net.tutsplus.com/?p=5919</guid>
		<description><![CDATA[<img src="http://nettuts.s3.amazonaws.com/388_rails/200x200.jpg" alt="20 Ruby on Rails Tutorials to Rule Them All" />]]></description>
			<content:encoded><![CDATA[<p>
Today, we&#8217;ll review twenty incredible Ruby on Rails tutorials that every developer should consider reading. Whether you&#8217;re a beginner who prefers video tutorials or an experienced dev, you&#8217;ll find an applicable tutorial here!</p>
<p><span id="more-5919"></span></p>
<h3>1. Try Ruby!</h3>
<p>
If you&#8217;re going to have to learn a brand new language, why not learn it interactively? The <a href="http://tryruby.hobix.com/">Try Ruby!</a> hands on tutorial is a step-by-step guide that shows you the basics of the Ruby language in 15-minutes. While it&#8217;s not strictly a Rails tutorial, it&#8217;s best to know the basics of Ruby before you dive right into the Rails framework.
</p>
<h3>2. Getting Started with Rails</h3>
<div class="tutorial_image">
<img src="http://nettuts.s3.amazonaws.com/388_rails/2.png" alt="Ruby Tutorials" />
</div>
<p>
This is <em>the</em> <a href="http://guides.rails.info/getting_started.html">definitive tutorial on Rails</a>. Written by the Rails team themselves, the tutorial shows you how to make a simple blog application. Simple, well documented, and perfect for beginners.
</p>
<h3>3. Using Ruby on Rails for Web Development on Mac OS X</h3>
<p>
If you&#8217;re a Rails developer, a Mac is an excellent choice for development as Rails comes shipped with Leopard. In fact, installing Rails on a Mac is as simple as typing:
</p>
<pre name="code" class="ruby">$ gem install rails</pre>
<p>
and you&#8217;re ready to start building apps.
</p>
<p>
Apple has a lengthy document on the <a href="http://developer.apple.com/tools/rubyonrails.html">benefits of using a Mac for Rails development</a>, as well as code examples and best use cases. The tutorial is a tad dated, but the guts of the article are timeless with respect to technologies and methods used.
</p>
<h3>4. UC Berkeley One-Day Rails Course</h3>
<p>
If you&#8217;ve got a whole day set aside to learn Rails, the <a href="http://radlab.cs.berkeley.edu/wiki/Ruby_on_Rails_1-day_course">One-Day Rails course</a> from UC Berkeley is fantastic. The learning course is broken down into 7 one-hour installments, and gives you the basics of Rails.
</p>
<h3>5. Why&#8217;s (Poignant) Guide to Ruby</h3>
<div class="tutorial_image">
<img src="http://nettuts.s3.amazonaws.com/388_rails/5.png" alt="Ruby Tutorials" />
</div>
<p>
Again, not a true Rails tutorial, <a href="http://poignantguide.net/ruby/">Why&#8217;s (Poigant) Guide to Ruby</a> is a fantastic and, ahem&#8230; <em>odd</em> way to learn Ruby. In fact, the free guide is so bizarre that I found it more useful than other learning resources because of its wit.
</p>
<blockquote><p>I’ll be straight with you. I want you to cry. To weep. To whimper sweetly. This book is a poignant guide to Ruby. That means code so beautiful that tears are shed. That means gallant tales and somber truths that have you waking up the next morning in the arms of this book. Hugging it tightly to you all the day long. If necessary, fashion a makeshift hip holster for Why’s (Poignant) Guide to Ruby, so you can always have this book’s tender companionship.</p>
</blockquote>
<p>
Odd? Yes. Effective? <em>Absolutely</em>.
</p>
<h3>6. Dominating Authlogic</h3>
<p>
<a href="http://github.com/binarylogic/authlogic/tree/master">Authlogic</a> is one of Rails most popular authentication systems. Yet because Authlogic is so robust, it can quickly become complex if you&#8217;re trying to utilize all the features and add different authentication scenarios.
</p>
<p>
Railscasts has <a href="http://railscasts.com/episodes/160-authlogic">an excellent screencast</a> on how to manage complex use cases of Authlogic. The screencast runs just over 14 minutes long.
</p>
<h3>7. Ruby on Rails on Oracle: A Simple Tutorial</h3>
<blockquote><p>Rails is an easy framework to work with, but like any technology it takes time to master.</p>
</blockquote>
<p>
Oracle has a hands-on tutorial on how to <a href="http://www.oracle.com/technology/pub/articles/haefel-oracle-ruby.html">build a simple product catalog with Rails</a> with an Oracle database.
</p>
<h3>8. Beta Invitations with Rails</h3>
<div class="tutorial_image">
<img src="http://nettuts.s3.amazonaws.com/388_rails/8.png" alt="Ruby Tutorials" />
</div>
<p>
If you&#8217;re building a web application that you want to marinate in &#8220;beta&#8221; status for a while, then you&#8217;ll probably want to construct some sort of beta invitation system. Railscasts has an excellent 22-minute tutorial on <a href="http://railscasts.com/episodes/124-beta-invitations">how to set up beta invitations</a>. It&#8217;s easier than you might think.
</p>
<h3>9. Migrations</h3>
<p>
For Rails newbies, migrations might be difficult to wrap your head around.
</p>
<blockquote><p>Migrations are a convenient way for you to alter your database in a structured and organized manner.</p>
</blockquote>
<p>
The Rails team has crated a nifty tutorial on <a href="http://guides.rails.info/migrations.html">everything migrations</a>, like how to create migrations from within your application, and how to use them to their full potential.
</p>
<h3>10. Rails Routing</h3>
<p>
Routing is another key aspect of Rails, and the ThinkFresh blog has a thorough tutorial on everything you need to <a href="http://thinkrefresh.com/posts/7-rails-101-routing">make routes work</a> from within your application. A great starter guide for Rails beginners.
</p>
<h3>11. Sexy Forms in Rails</h3>
<div class="tutorial_image">
<img src="http://nettuts.s3.amazonaws.com/388_rails/11.png" alt="Ruby Tutorials" />
</div>
<p>
If you&#8217;re not keen on making every single form by scratch, check out RubyPond&#8217;s <a href="http://rubypond.com/articles/2008/07/16/sexy-forms-in-rails/">Sexy Forms in Rails</a>. The tutorial shows how to build forms without having to fill in labels or worrying about formatting.
</p>
<p>
The tutorial eventually led to <a href="http://github.com/rubypond/semantic_form_builder/tree/master">FormBuilder</a>, a custom builder for creating accessible forms in Rails.
</p>
<h3>12. Developing iPhone Apps Using Ruby on Rails</h3>
<div class="tutorial_image">
<img src="http://nettuts.s3.amazonaws.com/388_rails/12.png" alt="Ruby Tutorials" />
</div>
<p>
<a href="http://www.ibm.com/developerworks/opensource/library/os-eclipse-iphoneruby1/index.html?S_TACT=105AGX44&#038;S_CMP=EDU">Developing iPhone Apps Using Ruby on Rails</a> is a three-part series by IBM. It covers things like setting up your development environment (the authors use Eclipse with the Aptana plugin), serving mobile content and how to detect iPhone browsers.
</p>
<h3>13. Monitoring Backgroundrb with God</h3>
<p>
<a href="http://god.rubyforge.org/">God</a>, (at least in Ruby terms), is a monitoring framework for Ruby applications. It monitors things like server processes and running tasks, to make sure that your application runs smoothly on your server.
</p>
<p>
Aside from server monitoring, you can use God to monitor other features of your Ruby apps as well. There&#8217;s a pretty heady tutorial on <a href="http://effectif.com/articles/monitoring-backgroundrb-with-god">how to monitor the Ruby job processing daemon BackgrounDRb</a>. You can build upon this tutorial to keep tabs on other aspects of your application as well.
</p>
<h3>14. Rails Security</h3>
<p>
Ruby on Rails is vulnerable to the same security problems that all other web apps can potentially have. The Rails team has put together a long guide on nearly all aspects of <a href="http://guides.rails.info/security.html">Rails security</a>. Learn about popular injection methods, Rails-specific problems and how to effectively handle sessions.
</p>
<h3>15. Make Your Own IM Bot In Rails</h3>
<div class="tutorial_image">
<img src="http://nettuts.s3.amazonaws.com/388_rails/15.png" alt="Ruby Tutorials" />
</div>
<p>
As the web becomes more connected and in real-time, more applications are starting to utilize IM functionality. Rubypond has a tutorial on <a href="http://rubypond.com/articles/2008/06/26/make-your-own-im-bot-in-ruby-and-interface-it-with-your-rails-app/">how to make an IM bot using Ruby</a>, and then how to interface the bot with Rails.
</p>
<p>
The tutorial is definitely for those with at least an intermediate understanding of Ruby and Rails.
</p>
<h3>16. Using Java Libraries in Rails Applications</h3>
<p>
<a href="http://netbeans.org">NetBeans</a>, the popular Java IDE, has a tutorial on how to use the <a href="http://www.netbeans.org/kb/docs/ruby/java-ruby.html">Java API in Rails applications</a>. This is an advanced tutorial, and only for those very familiar with both Java and Rails.
</p>
<h3>17. Building a Social Networking Site in Rails</h3>
<p>
As sites become more and more social, the demand for those social features in Rails applications will also go up. Here&#8217;s a tutorial on how to <a href="http://jimneath.org/2008/04/25/building-a-social-network-site-in-rails/">build aspects of a social networking site</a> using social networking plugins for Rails. You can pick and choose which features you&#8217;d like to add or leave in the tutorial.
</p>
<h3>18. How to Run a Stealth Rails Application</h3>
<p>
Aside from being a killer billing solution, <a href="http://www.freshbooks.com">Freshbooks</a> is a Rails application that <em>tries</em> to seem like a PHP application. In fact, they say they can pull it off with a single line of code in the routes.rb file:
</p>
<pre name="code" class="ruby">map.connect ':fake_filename.php', :controller => 'php', :action => 'dispatch'</pre>
<p>
Surprise!
</p>
<h3>19. Scaling Rails</h3>
<div class="tutorial_image">
<img src="http://nettuts.s3.amazonaws.com/388_rails/19.png" alt="Ruby Tutorials" />
</div>
<p>
With high-profile Rails sites like Twitter taking a toll on scalability last year, the public has consistently asked the question: Will Rails scale?
</p>
<p>
<a href="http://railslab.newrelic.com/scaling-rails">Scaling Rails</a> is a video series on how to effectively scale your Rails app through 13 screencasts. You&#8217;ll learn multiple types of caching and database optimization techniques, as well as how to optimize database structures.
</p>
<h3>20. Dropping and Sorting with Ajax and Scriptaculous</h3>
<p>
The name of this tutorial says it all. Learn how to write <a href="http://www.devarticles.com/c/a/Ruby-on-Rails/Dropping-and-Sorting-with-AJAX-and-scriptaculous/">draggables and sortables with Rails and Ajax</a>. The article has coding examples and can easily be followed by a Rails beginner.
</p>
<ul class="webroundup">
<li>Follow us on <a href="http://www.twitter.com/nettuts">Twitter</a>, or subscribe to the <a href="http://feeds.feedburner.com/nettuts" title="NETTUTS RSS Feed">NETTUTS RSS Feed</a> for more daily web development tuts and articles.</li>
</ul>
<p>
<script type="text/javascript"><!--digg_url = "post permalink (not digg url)"; // -->
</script><br />
<script src="http://digg.com/tools/diggthis.js" type="text/javascript"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://net.tutsplus.com/tutorials/ruby/20-ruby-on-rails-tutorials-to-rule-them-all/feed/</wfw:commentRss>
		<slash:comments>46</slash:comments>
		</item>
		<item>
		<title>Getting Started With Restful Authentication in Rails</title>
		<link>http://net.tutsplus.com/tutorials/ruby/getting-started-with-restful-authentication-in-rails/</link>
		<comments>http://net.tutsplus.com/tutorials/ruby/getting-started-with-restful-authentication-in-rails/#comments</comments>
		<pubDate>Wed, 24 Jun 2009 17:06:01 +0000</pubDate>
		<dc:creator>Noah Hendrix</dc:creator>
				<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://net.tutsplus.com/?p=5573</guid>
		<description><![CDATA[<img src="http://nettuts.s3.amazonaws.com/360_rails/200x200.png" alt="Getting Started With Restful Authentication in Rails" />]]></description>
			<content:encoded><![CDATA[<p>In this article, we will use restful_authentication to add a user system to a simple Rails application. This is great for those first starting out and need step-by-step directions for using this amazing plugin. At the end of the article, visitors will be able to create an account, reset their password, login, logout, and validate email addresses.
</p>
<p><span id="more-5573"></span></p>
<div class="tutorial_image">
<a href="http://nettuts.s3.amazonaws.com/360_rails/MyMovies.zip"><img src="http://nettuts.com/wp-content/themes/nettuts/site_images/button_src_nm.jpg"></a></p>
</div>
<h2>The Basics</h2>
<p>
  This portion of the tutorial is very basic. All we will do is generate a simple application that allows users to create/read/update/destroy a record containing a movie name and rating. I recommend advanced Rails developers skip to the third section which is where the restful_authentication code begins. <strong>Note</strong>: I did all of this on in OSX on a Mac, but it is not platform specific although you might need to prepend <strong>./</strong> to some of the commands so that Windows knows you are looking in the current directory. If you have any troubles I can help in the comments, or on twitter (<a href="http://twitter.com/noahhendrix">@noahhendrix</a>)
</p>
<h3>Generate the Application</h3>
<p>
  First we need to have rails generate the framework code. This is done by executing &#8220;rails MyMovies&#8221; in the terminal. &#8220;MyMovies&#8221; is what I chose to name this application and you are free to use that or anything else. This command creates a lot of files and folders most of which are of no concern to us, but are required for the application to work properly. After this executes will want to change into the newly created MyMovies directory.
</p>
<pre name="code" class="rails">
rails MyMovies
cd MyMovies
</pre>
<div class="tutorial_image"><img style="width: 600px;" src="http://nettuts.s3.amazonaws.com/360_rails/images/1.png" border="0" /></div>
<h3>Generate the Movie Model</h3>
<p>
  Now we are going to the power of Rails generators to quickly produce the code and database for our basic application. In the terminal run the command:
</p>
<pre name="code" class="rails">
script/generate scaffold Movie title:string rating:integer
</pre>
<div class="tutorial_image"><img style="width: 600px;" src="http://nettuts.s3.amazonaws.com/360_rails/images/2.png" border="0" /></div>
<p>
  Here we are telling rails that we want code generated to handle a &#8220;Movie&#8221; model, which as a string title and integer rating. Notice this will generate some more files, one of which is the database migration. This is where the magic of rails really shows itself, but first we must migrate the database.
</p>
<pre name="code" class="rails">
rake db:migrate
</pre>
<div class="tutorial_image"><img style="width: 600px;" src="http://nettuts.s3.amazonaws.com/360_rails/images/3.png" border="0" /></div>
<p>
  This command will setup the database and create the table with the appropriate columns. <strong>Note</strong>: Rails is smart enough to include ID, created_at, and updated_at columns for us. It will also manage these columns so we as developers never need to write code that sets these columns. Now lets look at the fruits of our labor, thats right we have written zero lines of code, but we already have a working application. Start up the server and navigate to <a href="http://localhost:3000/movies">http://localhost:3000/movies</a>. In your terminal type:
</p>
<pre name="code" class="rails">
script/server
</pre>
<h3>Enhancements</h3>
<p>
  You can try to create a movie and rating and see how easily everything works. The rails team really did a great job of allowing developers to quickly push code out with little effort, however that code is only a starting point. It is up to us the developers to make it our own and add the additional features and customizations for users. A good place to start is decide if there are any restrictions we will place on our model. For this example I decided we would require that the user only be able to rate the movie between 1 and 5 stars. Though there are others like making sure they enter a movie title and that the rating is a number. This is how handled in the movie model file.
</p>
<pre name="code" class="rails">
# app/models/movie.rb

validates_presence_of :title, :rating
validates_numericality_of :rating, :greater_than_or_equal_to => 1, :less_than_or_equal_to => 5
</pre>
<p>
  The syntax used in Rails is often verbose, but quite descriptive also. However a positive side effect is we never have to guess what the code we write means. We are telling rails before it saves to the database to verify that both title and rating are set, and as a further restriction rating must be a number between 1 and 5. Notice in the images below we get built in error reporting by default in rails.
</p>
<div class="tutorial_image"><img style="width: 600px;" src="http://nettuts.s3.amazonaws.com/360_rails/images/4.png" border="0" /></div>
<div class="tutorial_image"><img style="width: 600px;" src="http://nettuts.s3.amazonaws.com/360_rails/images/5.png" border="0" /></div>
<h3>User Interface Awareness</h3>
<p>
  Even as developers we are not exempt from considering the interface of applications we develop. Users need to immediately understand the purpose of any information displayed to them. In our application we have them set the rating, but we never say it needs to be an integer between 1 and 5. At first a user might enter a string such as &#8220;good&#8221;. We could put a label beside the text box that lists our requirements, but we can go a step further and explicitly let them choose between the options we want in a radio button format. Part of the Model View Controller (MVC) methodology of rails tells us that this is a view alteration and it is located within the views directory. First we must remove the line that creates the text box and its label, around line 11 in my code. Look for:
</p>
<pre name="code" class="rails">
# app/views/movies/edit.html.erb
# app/views/movies/new.html.erb

&lt;%= f.text_field :rating %&gt;
</pre>
<p>
  Alright now the new code below must be added to both the new and edit files because both contain forms where the model is modified.
</p>
<pre name="code" class="html">
# app/views/movies/edit.html.erb
# app/views/movies/new.html.erb

Rating
&lt;%= f.radio_button  :rating, 1 %&gt; &lt;%= f.label :rating_1, "1" %&gt;
&lt;%= f.radio_button  :rating, 2 %&gt; &lt;%= f.label :rating_2, "2" %&gt;
&lt;%= f.radio_button  :rating, 3 %&gt; &lt;%= f.label :rating_3, "3" %&gt;
&lt;%= f.radio_button  :rating, 4 %&gt; &lt;%= f.label :rating_4, "4" %&gt;
&lt;%= f.radio_button  :rating, 5 %&gt; &lt;%= f.label :rating_5, "5" %&gt;
</pre>
<p>
  Alright now lets look at this code closely. First we give the the rating label to tell the user what the radio buttons are for, then we move in the actual buttons. The first parameter for the radio_button method is the model attribute we are working with and the second is the value to send the server on submit. After each button we have a label to tell the user what rating the button corresponds to, the reason we pass in :rating_# is because when rails generates the radio button it gives it an id of attribute_value, so our labels hook into those values. Here is the what the new form looks like with the radio buttons, notice that when you edit a movie Rails automatically selects the radio button that corresponds to the previous rating from the database.
</p>
<div class="tutorial_image"><img style="width: 600px;" src="http://nettuts.s3.amazonaws.com/360_rails/images/6.png" border="0" /></div>
<p>
  This concludes the first part. In the previous section we got our movie rating application off the ground using the power of Rails generators and some basic view code. In the next section we will make our application a little more visually appealing by adding some graphics and CSS code to spruce up the views.
</p>
<h2>Styling</h2>
<h3>Layouts</h3>
<p>
  First we will look at layouts. Not getting into too much detail layouts hold the elements on a page that do not change across the application. For instance header, footer, and navigation typically (and rightfully so) stay consistent across a website. Even though our application is fairly trivial, a layout is important for consistency.
</p>
<p>
  Our goal is to include a logo, background image, and centered container for content on each page. First we need to create our application wide layout page. Rails is kind enough to create a model wide layout file, but this will not apply to the user pages when we get to that part so we need to change it to a global layout. This is easily done by renaming <strong>app/views/layouts/movies.html.erb</strong> to <strong>app/views/layouts/application.html.erb</strong>. Now we need to open the file and make a few changes. First lets wrap all of our content in a div called pagewrap. This is nice, because it gives us a bit more control in CSS than we normally get with just body. This can be done by simply including the opening just below the body, and closing it right above the body closing.
</p>
<pre name="code" class="html">
# app/views/layouts/application.html.erb
...
&lt;body&gt;

  &lt;div id="pagewrap"&gt;

    ...

  &lt;/div&gt;

&lt;/body&gt;
...
</pre>
<p>
  While we are in this file lets go ahead and include a CSS file we will create next. Find the line (9 in my file) that says <strong>stylesheet_link_tag &#8217;scaffold&#8217;</strong>  and append a comma and <strong>&#8217;style&#8217;</strong> to it so it looks like this:
</p>
<pre name="code" class="html">
# app/views/layouts/application.html.erb

&lt;%= stylesheet_link_tag 'scaffold', 'style' %&gt;
</pre>
<p>
  This is a helper method provided by rails that creates the &lt;link&gt; tag for us, and links to the style.css file in our stylesheets directory. In <strong>public/stylesheets</strong> create a file called <strong>style.css</strong>. Because this is not really a CSS tutorial I will only graze over the declarations.
</p>
<pre name="code" class="css">
# public/stylesheets/style.css

html, body {
  background-image: url(/images/bg_body.jpg);
}

#pagewrap {
  -moz-border-radius: 10px;
  -webkit-border-radius: 10px;

  margin: 0 auto;
  padding: 10px;
  width: 900px;

  /* logo */
  background: white url(/images/logo.png) no-repeat;
  padding-top: 72px;
}
</pre>
<p>
  I am applying a background image to the body tag, so that is will cover the entire page. The pagewrap element we created earlier is given rounded corners (only in Safari and Firefox sorry IE), centered using margin, some padding to push content in, 900px width, and a non-repeating background image that is our logo. The content is pushed down 72px to accommodate the logo, kind of a hack but just an easy way to throw the logo on the page. Unfortunately I can&#8217;t distribute the background image or logo because they were created using pieces from a <a href="http://themeforest.net/item/mezzo-folio-designer-portfolio/32731"></a>template I bought on <a href="http://themeforest.net">ThemeForest.net</a>. But there doesn&#8217;t that look so much better now?
</p>
<div class="tutorial_image"><img style="width: 600px;" src="http://nettuts.s3.amazonaws.com/360_rails/images/7.png" border="0" /></div>
<h3>Adding Stars</h3>
<p>
  The index page is pretty lame as-is because it simply list the title of the movie and an integer for the rating. Let&#8217;s add some CSS magic to make that a little more pretty. First lets update <strong>app/views/movies/index.html.erb</strong>, by changing the table cell that holds the rating, on line 12. We will wrap the rating in a div with a special class containing the number of stars to show. We also make use of the pluralize helper method in Rails which will output a number passed to it and append a word after the number making it plural if necessary.
</p>
<pre name="code" class="html">
# app/views/movies/index.html.erb

&lt;td&gt;&lt;div class="star-&lt;%=h movie.rating %&gt; rating"&gt;&lt;%=pluralize movie.rating, "Star" %&gt;&lt;/div&gt;&lt;/td&gt;
</pre>
<p>
  Alright now lets create the CSS code necessary. <strong>Note</strong>: I did not include the image in the HTML markup so that if a user has CSS disabled they won&#8217;t see any stars just something like &#8220;3 Stars.&#8221;
</p>
<pre name="code" class="css">
# public/stylesheets/style.css

.rating {
  background: url(/images/stars.png) no-repeat;
  height: 26px;
  overflow: hidden;
  text-indent: -1000px;
}
.star-5 { width: 115px; }
.star-4 { width: 92px; }
.star-3 { width: 69px; }
.star-2 { width: 46px; }
.star-1 { width: 23px; }
</pre>
<p>
  We apply a non-repeating background image of 5 stars to all the rating divs, and then change the width (in 20% increments) to allow hiding of stars. We also push the &#8220;# Stars&#8221; text off the page with a negative text-indent, since the stars are plain enough language to not require actual words too.
</p>
<div class="tutorial_image"><img style="width: 600px;" src="http://nettuts.s3.amazonaws.com/360_rails/images/8.png" border="0" /></div>
<h3>Optional: Removing The Show Page</h3>
<p>
  One last thing I did was remove links to the show page. It seemed a bit redundant to include it since the index page showed all the relevant information. You can do the same by opening <strong>app/views/movies/index.html.erb</strong> and removing line 13, the link_to the show page. You also need to open <strong>app/controllers/movies_controller.rb</strong> and update lines 48 and 65 call to redirect_to, make the parameter <strong>movies_url</strong> instead.
</p>
<h2>The restful_authentication Plugin</h2>
<p>
  Now that we have made it through the basics, lets add users! The purpose of the first half of this tutorial was to simulate the legacy application you have already created. So from this point on you can easily apply what we learn to any application you create. The great thing about the restful_authentication plugin is that it abstracts the authentication logic away from the other models and makes it fairly quick and painless to implement.
</p>
<h3>Install restful_authentication</h3>
<p>
  First things first we need to install the restful_authentication plugin, stop the server by pressing <strong>CTRL+C</strong>, if you have it running. The <a href="http://github.com/technoweenie/restful-authentication/tree/master">GitHub</a> page for restful_authentication has instructions on installing, but here is the reader&#8217;s digest version:
</p>
<pre name="code" class="rails">
script/plugin install http://github.com/technoweenie/restful-authentication.git restful_authentication
</pre>
<div class="tutorial_image"><img style="width: 600px;" src="http://nettuts.s3.amazonaws.com/360_rails/images/9.png" border="0" /></div>
<p>
  Passing in the second <strong>restful_authentication</strong> tells rails we want to rename the plugin folder to that instead of <strong>restful-authenticatoin</strong>. The reasoning is explained under the header of <strong>Installation</strong> for those who are interested. Alright now this commands basically goes out to the server and fetches all the restful_authentication files and copies them to your server. It also creates a generator script that we can run to create the necessary controllers, models, and views in our application folder.
</p>
<pre name="code" class="rails">
script/generate authenticated user sessions --include-activation
</pre>
<p>
  Using the authenticated generator we say we want to call the model that handles user information user, and the model that handles the sessions called sessions, easy enough right? But why do we separate these? If you really think about about it registering a user and retrieving their information is similar to authenticating them, but really it is very different too. One is storing long term login information on the user and the other is more temporary and is erased once they logout. So it really makes a lot of sense to split them up in our design. We also pass in the include-activation flag so that it generates the necessary mailers for activating user accounts through email.
</p>
<p>
  Alright that now we have the files in the application folder, but we are not quite done in the terminal. The generator above also created some migrations for us that creates users and sessions tables in our database, but now we need to associate users with their movie records. Let&#8217;s use the migrations generator to add a user_id column to the movies table.
</p>
<pre name="code" class="rails">
script/generate migration add_user_id_to_movie user_id:integer
</pre>
<div class="tutorial_image"><img style="width: 600px;" src="http://nettuts.s3.amazonaws.com/360_rails/images/10.png" border="0" /></div>
<p>
  Rails 2.0 brought some really nifty automation for the migrations generator. Because of the name schema <strong>add_user_it_to_movie</strong> rails will assume what we mean and create a schema that does just that. So all we are left to do is run
</p>
<pre name="code" class="rails">
rake db:migrate
</pre>
<div class="tutorial_image"><img style="width: 600px;" src="http://nettuts.s3.amazonaws.com/360_rails/images/11.png" border="0" /></div>
<p>
  and our database is up to date. If you want to see the migrations file it created to get a feel of what we did you can check out <strong>app/db/migrate</strong> and look for the add_user_id_to_movie.rb file. Ok, we are all done in the terminal for now!
</p>
<h3>Associating Users and Movies</h3>
<p>
  In order for a user to &#8220;own&#8221; a movie record we must tell rails that they do. This is down through associations declared in the models. First lets update the user model created by our generator, <strong>app/models/user.rb</strong>. I usually add the following code right above the first method declaration, activate in this case.
</p>
<pre name="code" class="rails">
#app/models/user.rb

has_many  :movies
</pre>
<p>
  This is pretty straight-forward, we are telling rails that user has many movie records associated with their account. Now lets inform the movie model of the associate in <strong>app/models/movie.rb</strong>. Add this code right below our validation methods from earlier.
</p>
<pre name="code" class="rails">
#app/models/movie.rb

belongs_to  :user
</pre>
<p>
  Similar to above we just are saying that each individual movie record belongs to a user. Now the beauty of these associations is Rails now assumes our database has a user_id column in the movies table, which we of course already do. That is all the work we have to do no foreign keys, no custom code it is just given to us out of the box more or less.
</p>
<h3>Routes</h3>
<p>
  This is more of a user experience modification, but something all applications should include. Currently if a user wanted to sign up the url is <strong>example.com/users/new</strong> or if they wanted to login it is <strong>example.com/sessions/new</strong>, a bit verbose in my opinion. So we will add some custom routes in <strong>config/routes.rb</strong>, mine went in around line 8.
</p>
<pre name="code" class="rails">
# config/routes.rb

map.activate '/activate/:activation_code', :controller => 'users', :action => 'activate'
map.signup '/signup', :controller => 'users', :action => 'new'
map.login '/login', :controller => 'sessions', :action => 'new'
map.logout '/logout', :controller => 'sessions', :action => 'destroy'
</pre>
<p>
  As you can see here we are declaring active, signup, login, and logout for their obvious counterparts. This will make our URLs more sensible and easy to remember. Notice that activate requires a string passed in which will be the activation code we send out in emails to users to validate email addresses.
</p>
<h3>Validating Email Addresses</h3>
<p>
  It is common practice with many websites to require users to validate email addresses by clicking a link in an email sent to the address they provide. In other languages and frameworks this is somewhat difficult, but the restful_authentication plugin and rails mailers makes this advanced functionality very easy. However before we can send out emails we need to tell rails how to authenticate with our SMTP server. Now this varies from host to host, and you will need to contact your host to determine how to fill in these settings. <strong>Note</strong>: You will need to create the file config/initializers/mail.rb first.
</p>
<pre name="code" class="rails">
# config/initializers/mail.rb

ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.smtp_settings = {
	:address => "mail.example-domain.com",
	:port => 25,
	:domain => "www.example-domain.com",
	:authentication => :login,
	:user_name => "user@example-domain.com",
	:password => "secret"
}
</pre>
<p>
  While we are setting up defaults we should define the URL of our website we will use in all our emails. You might wonder why we would do this, and reason is to future-proof our application. For instance, while we are developing locally the domain is <strong>localhost:3000/</strong>, and presumably our production domain is different. If at some point in the future the production URL changes we can update it in one place and not worry about other missing other changes. But where do we site these defaults? Rails created some configuration files that are loaded depending on the environment we are in: development, testing, or production. Starting with development we must modify <strong>config/environments/development.rb</strong>, at line 19.
</p>
<pre name="code" class="rails">
# config/environments/development.rb

SITE_URL  = "localhost:3000"
</pre>
<p>
  And likewise in <strong>config/environments/production.rb</strong> at line 30.
</p>
<pre name="code" class="rails">
# config/environments/production.rb

SITE_URL  = "noahhendrix.com"
</pre>
<p>
  Now we need to update the user_mailer model file, <strong>app/models/user_mailer.rb</strong>, to use our newly create <strong>SITE_URL</strong> variable. These changes need to be made on lines 6, 13, and 20 remove <strong>YOURSITE</strong> and replace it with <strong>#{SITE_URL}</strong>. On line 19 you need to update the email address to your own.
</p>
<p>
  Here is what the email asking them to activate their account looks like.
</p>
<div class="tutorial_image"><img style="width: 600px;" src="http://nettuts.s3.amazonaws.com/360_rails/images/12.png" border="0" /></div>
<p>
  They also receive an email once the account is activated
</p>
<div class="tutorial_image"><img style="width: 600px;" src="http://nettuts.s3.amazonaws.com/360_rails/images/13.png" border="0" /></div>
<h3>Updating our Controllers</h3>
<p>
  The movies controller that rails created for us was helpful before we added a user system, but now we want to only allow users to cretate, read, update, and destroy their own movies and prevent them from seeing other users&#8217; movies. This is done by modifying the movies controller and having it add a user_id column restriction on all queries to the movies table.
</p>
<p>
  We are going to update a bunch of lines and because they are so pretty much the same we won&#8217;t go over them individually. Essentially we are telling the controller to restrict all finds to the <strong>current_user</strong> variable (i.e. add &#8220;WHERE user_id = ##&#8221; to the database queries). The <strong>current_user</strong> variable is something restful_authentication gives us to use in our controller for this specific reason. I&#8217;ve included the approximate line numbers, but if they are different for you then know that we are only modifying the methods: index, show, edit, create, update, and destroy. <strong>Note</strong>: the variable Movie is changed to movies because we are accessing it through the user which comes from when we said a user has many movies.
</p>
<pre name="code" class="rails">
# app/controllers/movies_controller.rb

Line 8: @movies = current_user.movies
Line 20: @movie  = current_user.movies.find(params[:id])
Line 42: @movie  = current_user.movies.find(params[:id])
Line 49: @movie  = current_user.movies.create(params[:movie])
Line 67: @movie  = current_user.movies.find(params[:id])
Line 85: @movie  = current_user.movies.find(params[:id])
</pre>
<p>
  While we have this file open at the top (line 2) we need to add a before filter. This tells rails that before it runs any of the methods below it needs to first run a method we provide.
</p>
<pre name="code" class="rails">
# app/controllers/movies_controller.rb

before_filter :login_required
</pre>
<p>
  The method :login_required is provided by the plugin and basically will check if the user is logged in, and if not will redirect them to the login page.
</p>
<p>
  Alright not too bad, right? We have a few last things to clean up before the plugin is fully functioning. In <strong>app/controllers/sessions_controller.rb</strong> and <strong>app/controllers/users_controller.rb</strong> there is an include statement that need to be removed, and added to <strong>app/controllers/application_controller.rb</strong>. This line includes the necessary back end files that the plugin uses to manage the users and sessions. I put mine at line 5.
</p>
<pre name="code" class="rails">
# app/controllers/application_controller.rb

include AuthenticatedSystem
</pre>
<p>
  If you curious where it is pulling this file from, you can find it in <strong>lib/authenticated_system.rb</strong>.
</p>
<h2>Adding Password Reset</h2>
<h3>Updating The Users Controller</h3>
<p>
  We need to add two methods to the users controller, <strong>app/controllers/users_controllers.rb</strong>, that will take care of the form for users to reset their password. However, before we dive into code lets take a second to discuss our plan. We want to allow a user to click a link that says they forgot their password. They will then be taken to a page asking what email address they used when creating their account, once they submit that we will fire off an email with a link containing a special hash that will they can click. Once they open the link in their email they will have a form to choose a password, and confirm it.
</p>
<p>
  Alright lets look at each function individually starting with forgot.
</p>
<pre name="code" class="rails">
# app/controllers/users_controller.rb

def forgot
  if request.post?
    user = User.find_by_email(params[:user][:email])

    respond_to do |format|
      if user
        user.create_reset_code
        flash[:notice] = "Reset code sent to #{user.email}"

        format.html { redirect_to login_path }
        format.xml { render <img src='http://net.tutsplus.com/wp-includes/images/smilies/icon_mad.gif' alt=':x' class='wp-smiley' /> ml => user.email, :status => :created }
      else
        flash[:error] = "#{params[:user][:email]} does not exist in system"

        format.html { redirect_to login_path }
        format.xml { render <img src='http://net.tutsplus.com/wp-includes/images/smilies/icon_mad.gif' alt=':x' class='wp-smiley' /> ml => user.email, :status => :unprocessable_entity }
      end
    end

  end
end
</pre>
<div class="tutorial_image"><img style="width: 600px;" src="http://nettuts.s3.amazonaws.com/360_rails/images/16.png" border="0" /></div>
<p>
  Here is the action referring to the form where they enter their email address. First we check to see if they have submitted the form via a post request, if not we do nothing because we are waiting for the form to be submitted. Once we have post data we find the users information using the provided email address to make sure they exist. We are using a respond_to format block so that we can respond to both xml and html requests. In this tutorial we won&#8217;t use the XML format, but it is good to provide it for web services. Now you will see we have a simple if statement saying if user is not nil (implied) we want to run the method create_reset_code and notify the user via a flash method that they need to check their email for a reset link. If the user doesn&#8217;t exist we let them know that as well.
</p>
<p>
  Alright now lets look at the reset action, the one they see after they click the link in their email.
</p>
<pre name="code" class="rails">
# app/controllers/users_controller.rb

def reset
  @user = User.find_by_reset_code(params[:reset_code]) unless params[:reset_code].nil?
  if request.post?
    if @user.update_attributes(:password => params[:user][:password], :password_confirmation => params[:user][:password_confirmation])
      self.current_user = @user
      @user.delete_reset_code
      flash[:notice] = "Password reset successfully for #{@user.email}"
      redirect_to root_url
    else
      render :action => :reset
    end
  end
end
</pre>
<div class="tutorial_image"><img style="width: 600px;" src="http://nettuts.s3.amazonaws.com/360_rails/images/17.png" border="0" /></div>
<p>
  First we find the users information through the reset code, to make sure that they exist in the database. If there is user data found we log them, and present the form to reset their password. Next we check to see if they are just loading the form or if they have already submitted it. If there is post data we update the password to the one they supplied. We set the current_user to that user, and remove the reset code so no one else can use the link to change their password. We give them a flash notice that confirms the reset. If we can&#8217;t update the password we send them back to the password page with errors.
</p>
<h3>Updating the User Model</h3>
<p>
  Some of this is pretty confusing because we haven&#8217;t fully implemented some methods we used such as: create_reset_code, recently_reset?, and delete_reset_code. We will put these in the user model, <strong>app/models/user.rb</strong>, right above the word protected towards the bottom.
</p>
<pre name="code" class="rails">
#app/models/user.rb

#reset methods
def create_reset_code
  @reset = true
  self.attributes = {:reset_code => Digest::SHA1.hexdigest( Time.now.to_s.split(//).sort_by {rand}.join )}
  save(false)
end

def recently_reset?
  @reset
end

def delete_reset_code
  self.attributes = {:reset_code => nil}
  save(false)
end
</pre>
<p>
  In the create_reset_code function we are setting an instance variable <strong>@reset</strong> to true so that our application can keep remember that they are have recently reset their password. Then we are setting a reset_code in the database (which we have yet added a column for) to a hash of the current time to make it unique. Then we save that reset_code to the database, the false parameter tells rails to ignore validations which we can do because we set the code ourselves not users.
</p>
<p>
  The recently_reset? method is just so we can check if the @reset variable is true or false. And finally the delete_reset_code does exactly what it&#8217;s name infers, remove the reset code from the database.
</p>
<h3>Creating the Forgot and Reset Views</h3>
<p>
  We&#8217;ve talked about the forms the user needs to fill out in order to reset their password, lets go a head and create those. First in the directory <strong>app/views/users/</strong> called <strong>forgot.html.erb</strong>.
</p>
<pre name="code" class="html">
# app/views/users/forgot.html.erb

&lt;%= error_messages_for :user %&gt;

&lt;% form_for :user do |f| -%&gt;
  &lt;p&gt;
    Reset Password Request
  &lt;/p&gt;

  &lt;p&gt;
    &lt;label for="email"&gt;Email&lt;/label&gt;&lt;br /&gt;
    &lt;%= f.text_field :email %&gt;
  &lt;/p&gt;

  &lt;p&gt;
    &lt;%= link_to "Cancel", login_path %&gt;
    &lt;%= submit_tag 'Submit' %&gt;
  &lt;/p&gt;
&lt;% end -%&gt;
</pre>
<div class="tutorial_image"><img style="width: 600px;" src="http://nettuts.s3.amazonaws.com/360_rails/images/15.png" border="0" /></div>
<p>
  This is a pretty generic form, where we ask the user for their email. Now we need to create the form to reset the password in the same directory as above create a file called <strong>reset.html.erb</strong>.
</p>
<pre name="code" class="html">
# app/views/users/reset.html.erb

&lt;%= error_messages_for :user %&gt;

&lt;% form_for :user do |f| -%&gt;
  &lt;p&gt;
    Pick a new password for &lt;span&gt;&lt;%= @user.email %&gt;&lt;/span&gt;
  &lt;/p&gt;

  &lt;p&gt;
    &lt;label for="password"&gt;Password&lt;/label&gt;&lt;br /&gt;
    &lt;%= f.password_field :password %&gt;
  &lt;/p&gt;

  &lt;p&gt;
    &lt;label for="password"&gt;Confirm Password&lt;/label&gt;&lt;br /&gt;
    &lt;%= f.password_field :password_confirmation %&gt;
  &lt;/p&gt;

  &lt;p&gt;
    &lt;%= submit_tag 'Reset' %&gt;
  &lt;/p&gt;
&lt;% end -%&gt;
</pre>
<div class="tutorial_image"><img style="width: 600px;" src="http://nettuts.s3.amazonaws.com/360_rails/images/19.png" border="0" /></div>
<h3>Emailing the User A Reset Link</h3>
<p>
  Alright now that we have the forms setup lets modify the user mailer class to send the reset links out. Since we are working with views lets start there. If a traditional view translates roughly to a webpage then a mailer view would translate to an email. Basically this is the basic layout of the email we want to send the user, leaving spots for variables our controller will provide. The file we are going to create is <strong>app/views/user_mailer/reset_notification.html.erb</strong>, and the insert this code:
</p>
<pre name="code" class="html">
# app/views/user_mailer/reset_notification.html.erb

Request to reset password received for &lt;%= @user.login %&gt;

Visit this url to choose a new password:

&lt;%= @url %&gt;
(Your password will remain the same if no action is taken)
</pre>
<div class="tutorial_image"><img style="width: 600px;" src="http://nettuts.s3.amazonaws.com/360_rails/images/18.png" border="0" /></div>
<p>
  This is all pretty generic mark up, notice that we have a space for the url and the users login name. We also tell them that if they do nothing the password will not be changed. Now lets go into <strong>app/models/user_mail.rb</strong> and create the reset_notification method, this is where our view gets the user login and reset url variables. Insert this code somewhere after the activation method, but above protected.
</p>
<pre name="code" class="rails">
# app/models/user_mailer.rb

...
def reset_notification(user)
  setup_email(user)
  @subject    += 'Link to reset your password'
  @body[:url]  = "#{SITE_URL}/reset/#{user.reset_code}"
end
...
</pre>
<p>
  Here we are doing a few things. First we call the setup_email method that is declared under protected (protected means only this class can call that method), which is some generic email setup things. We append a string to the subject to help the user identify the purpose of the email from the subject. Next we set that URL we talked about earlier notice we are using the <strong>#{SITE_URL}</strong> variable we set earlier. The reset_code variable comes from the user model that we set earlier using the create_reset_code method, remember that?
</p>
<p>
  One more model that we need to update, <strong>app/models/user_observer.rb</strong>. Basically this is where we say to send that email if the <strong>@reset</strong> variable is true. These methods are executed whenever the user is interacted with, in this case after we save it to the database we want to check if they need to get a reset email. After the line that sends the activation email add this code.
</p>
<pre name="code" class="rails">
# app/models/user_observer.rb

...
UserMailer.deliver_reset_notification(user) if user.recently_reset?
...
</pre>
<p>
  Alright lets update one more file before we move into the terminal to add the reset_code column. Remember that URL the user is emailed? Well we need to set that up in the routes file, <strong>config/routes.rb</strong>. On the line below where we setup the logout route add these two lines:
</p>
<pre name="code" class="rails">
# config/routes.rb

map.forgot    '/forgot', :controller => 'users', :action => 'forgot'
map.reset     'reset/:reset_code', :controller => 'users', :action => 'reset'
</pre>
<p>
  This is just like the above routes, we are mapping friendly URLs to the proper controllers and actions. Alright, lets move into the terminal. So now we are going to use the same migration generator we used for adding user_id to the movies table. So this code will look really familiar.
</p>
<pre name="code" class="rails">
script/generate migration add_reset_code_to_user reset_code:string
</pre>
<p>
  Don&#8217;t forget to run
</p>
<pre name="code" class="rails">
rake db:migrate
</pre>
<p>
  to update the database.
</p>
<div class="tutorial_image"><img style="width: 600px;" src="http://nettuts.s3.amazonaws.com/360_rails/images/20.png" border="0" /></div>
<h2>Cleaning Up Loose Ends</h2>
<h3>Setting the Default Root Page</h3>
<p>
  First we need to delete the file <strong>public/index.html</strong>. This is the page and will override the default controller we will set. Next open <strong>config/routes.rb</strong>, and uncomment line 46 (the one starting <strong>map.root</strong>). Change <strong>welcome</strong> to <strong>movie</strong>, this tells rails to render the movie controller as our default if someone navigates to <strong>localhost:3000/</strong> or the root of our production domain.
</p>
<h3>Adding Sign Up, Reset, and Logout links</h3>
<p>
  Alright now we get to move to the views. in <strong>app/views/sessions/new.html.erb</strong> we should remove lines 8 and 11 to allow our users to remember their session so they do not have to re-login each time they visit. On line 11 there is a paragraph tag we need to add sign up and forget passwords links within that element.
</p>
<pre name="code" class="html">
# app/views/sessions/new.html/erb

&lt;%= link_to 'Sign Up', :signup %&gt;
&lt;%= link_to 'Forgot Password?', :forgot %&gt;
</pre>
<div class="tutorial_image"><img style="width: 600px;" src="http://nettuts.s3.amazonaws.com/360_rails/images/14.png" border="0" /></div>
<p>
  Users are now able to easily sign up, login, or reset their password but we need to include a logout link once they are logged in so they can end their session. We will do this in the application layout file, <strong>app/views/layouts/application.html.erb</strong>, so that it appears on all pages. I added mine right above the flash messages, but below the pagewrap div.
</p>
<pre name="code" class="html">
# app/views/layouts/application.html.erb
&lt;div class="user"&gt;
  &lt;%= link_to "Logout", :logout unless !logged_in? %&gt;
&lt;/div&gt;
</pre>
<p>
  Notice that we say to include the link unless logged_in? is false, logged_in? is a helper the plugin provides that returns true if the user is logged in and false if they are not, and of course we only want to the link if they are actually logged in.
</p>
<p>
  While we are here lets add another flash message type, alert. This is to display errors to the user passed in from the controllers. Below the existing one add this line.
</p>
<pre name="code" class="html">
# app/views/layouts/application.html.erb

&lt;p style="color: red"&gt;&lt;%= flash[:alert] %&gt;&lt;/p&gt;
</pre>
<h3>Preventing Auto-Login on Sign Up</h3>
<p>
  You might have noticed that when you sign up the application logs you in without first requiring the email verfication, although it prevents any subsequent logins. This is something included in the default user controller where if the user passes validation they are logged in by setting current_user to the user model just created. In our application this is a bug because we want the user to first authenticate their email address. We can fix this behavior in <strong>app/controllers/users_controller.rb</strong> around line 16 we need to remove, or comment out, where it sets <strong>current_user = @user</strong>.
</p>
<p>
  Also as a helpful hint to users we should modify line 17 where it tells the user they successfully signed up to something that instructs them to check their email.
</p>
<pre name="code" class="rails">
# app/controllers/users_controller.rb

flash[:notice] = "Thanks for signing up! Please check your email to activate your account."
</pre>
<p>
  Alright that is all we need to do for our basic user authentication. I hope this has helped as a step-by-step walkthrough of how to install and use restful_authentication in your rails application. I know that this is very simplistic so post any desired customizations in the comments, or contact me on twitter (<a href="http://twitter.com/noahhendrix">@noahhendrix</a>) and I will try to address them. Thanks for reading!
</p>
<ul class="webroundup">
<li>Follow us on <a href="http://www.twitter.com/nettuts">Twitter</a>, or subscribe to the <a href="http://feeds.feedburner.com/nettuts" title="NETTUTS RSS Feed">NETTUTS RSS Feed</a> for more daily web development tuts and articles.</li>
</ul>
<p>
<script type="text/javascript"><!--digg_url = "post permalink (not digg url)"; // -->
</script><br />
<script src="http://digg.com/tools/diggthis.js" type="text/javascript"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://net.tutsplus.com/tutorials/ruby/getting-started-with-restful-authentication-in-rails/feed/</wfw:commentRss>
		<slash:comments>27</slash:comments>
		</item>
		<item>
		<title>Ruby on Rails for Designers</title>
		<link>http://net.tutsplus.com/tutorials/ruby/ruby-on-rails-for-designers/</link>
		<comments>http://net.tutsplus.com/tutorials/ruby/ruby-on-rails-for-designers/#comments</comments>
		<pubDate>Thu, 23 Apr 2009 15:13:20 +0000</pubDate>
		<dc:creator>Alex Coomans</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[ruby on rails]]></category>

		<guid isPermaLink="false">http://net.tutsplus.com/?p=4455</guid>
		<description><![CDATA[<img src="http://nettuts.s3.amazonaws.com/299_ror/200x200.jpg" alt="Ruby on Rails for Designers" />]]></description>
			<content:encoded><![CDATA[<p>Ruby on Rails is an open-source web framework that&#8217;s optimized for programmer happiness and sustainable productivity. It lets you write beautiful code by favoring convention over configuration. </p>
<p>This is the way Ruby on Rails promotes itself &#8211; but in my words, it is an incredible framework that can really make your life much easier. You can learn more at their site <a href="http://rubyonrails.org">http://rubyonrails.org</a></p>
<p><span id="more-4455"></span></p>
<h3>Step 1- Installing Ruby on Rails</h3>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/299_ror/1.jpg" border="0" /></div>
<p>Installing Ruby on Rails (also often shortened to RoR) is fairly painless on most systems, but you will need to be comfortable opening up the terminal. The Ruby on Rails <a href="http://rubyonrails.org/download">download page</a> provides links to get started, and I will reproduce them here to save you a bit of time. Just as a note, these are the places to get Ruby, which is what Rails is programmed in, and we will be installing Rails in a minute. To learn more about the language, review the <a href="http://ruby-lang.org">Ruby site</a></p>
<ul>
<li><b>Windows:</b> <a href="http://rubyforge.org/frs/?group_id=167">One-Click Ruby Installer</a> (I recommend using 1.8.6-26 Final Release)</li>
<li><b>Mac OS X 10.4:</b> Ships with broken Ruby but you can follow the <a href="http://hivelogic.com/articles/view/ruby-rails-mongrel-mysql-osx">amazing guide</a> by Dan Benjamin</li>
<li><b>Mac OS X 10.5:</b> If you install the Developer Tools from Apple you will be set. Try either your installation discs or <a href="http://developer.apple.com/mac/">Apple&#8217;s Developer Site</a> and download Xcode</li>
<li><b>Linux:</b> While this may vary for each distribution, you will need to install ruby, irb, &amp; rdoc</li>
</ul>
<p>Now that we&#8217;ve downloaded Ruby, make sure you have <a href="http://www.rubygems.org">RubyGems</a>, which is a package manager for Ruby. </p>
<div class="tutorial_image">
<img src="http://nettuts.s3.amazonaws.com/299_ror/rubypackage.png" alt="Ruby Package" />
</div>
<p>To test if you have RubyGems, run the following in terminal:</p>
<pre name="code" class="html">gem -v</pre>
<p>As of this writing, 1.3.2 is the latest version. To update if you don&#8217;t have the latest version, run the following, and if you are on a Mac, put sudo in the front.</p>
<pre name="code" class="html">gem update --system</pre>
<p>If you won&#8217;t be using RubyGems, follow these steps:</p>
<ol>
<li>Download the latest release of RubyGems <a href="http://rubyforge.org/frs/?group_id=126">here</a>.</li>
<li>Extract the package</li>
<li>Change into the directory in your terminal (cd is the command)</li>
<li>Run this in the terminal: ruby setup.rb (Add sudo in front of the command for Linux &amp; Mac OS X users, you will also need to continue that for all gem install commands)</li>
</ol>
<p>If you have a Linux system, you should be able to install RubyGems through your package manager, but I prefer the method above. If you have any more problems, check out the <a href="http://rubygems.org/read/chapter/3">installation documentation</a> at the RubyGems site.</p>
<h3>Installing Rails</h3>
<p>Now that we have the latest version of RubyGems, let&#8217;s install Rails:</p>
<pre name="code" class="html">gem install rails</pre>
<p>It will take a few minutes to install Rails and all of its&#8217; dependancies.</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/299_ror/2.jpg" border="0" /></div>
<h3>Step 2 &#8211; Creating an Application</h3>
<p>So now that we have Ruby, RubyGems, and Rails installed, let&#8217;s create a project! To create a new project, you will use the Rails command to create new projects. We will create a simple project named &#8220;blog.&#8221; <u>Note:</u> This will create the app folder in the current directory you are in terminal, so make sure you change into the directory you want the app to be stored in.</p>
<pre name="code" class="html">rails blog</pre>
<p>You should see something like this fly by:</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/299_ror/3.jpg" border="0" /></div>
<p>Next, open the project in your favorite text editor/IDE. I personally love <a href="http://macromates.com/">TextMate</a>, -while only for Mac OS X, there are some great clones which are also available.</p>
<h3>Folder Structure</h3>
<p>The folder structure of a Ruby on Rails will look similar to the following:</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/299_ror/4.jpg" border="0" /></div>
<p>There are three folders any developer or designer will need to work with on a daily basis: the app, config, and public folders. Please review the short explanations for each of the folders:</p>
<ul>
<li><b>app:</b> This is where your application&#8217;s logic lives.
<ul>
<li><b>controllers:</b> This is where Rails looks for the controller classes. In short, these receive the requests.</li>
<li><b>helpers:</b> Helpers live in this directory and assist the controllers, models, and views</li>
<li><b>models:</b> Each of these basically represents a table in the database, so finding information and setting up your application is dead simple</li>
<li><b>views:</b> what the user sees
<ul>
<li><b>layouts:</b> these are each of the layouts you can define a controller to use. Makes templating very easy.</li>
<li><b>all the other ones:</b> While in our application we currently don&#8217;t have any, each of the other folders that will be in this folder represent and relate back to the controllers, and the files that will be in here correspond to the actions in the controller</li>
</ul>
</li>
</ul>
</li>
<li><b>config:</b> This folder holds all of your app&#8217;s settings. Some specific files:
<ul>
<li><b>database.yml:</b> This file holds your database settings</li>
<li><b>environment.rb:</b> This file holds the Rails settings for your application</li>
<li><b>environements/:</b> This folder holds the configuration settings for each of the specific environments: development, test, and production</li>
<li><b>routes.rb:</b> This file holds the settings for the URL schema, as well as specific URL and where to send the requests</li>
</ul>
</li>
<li><b>db:</b> This folder will end up holding your database (if you use sqllite), your database schema, and all of your database migrations (changes to the structure)</li>
<li><b>doc:</b> This folder will hold all of the documentation generated by rake doc:app</li>
<li><b>lib:</b> The files in here contain application specific code that doesn&#8217;t belong in your controllers.</li>
<li><b>log:</b> Rails stores the logs in here, four of them. One for server specific stuff in server.log, and one for each environments.</li>
<li><b>public:</b> This folder contains all of the files that will not change as much. Rails looks for files her before trying to go to a controller. Javascripts are stored in the javascripts folder, images in the images folder, and stylesheets in the stylesheets folder. Static files like robots.txt and other html files can also be stored here. Make sure you delete the index.html file because that will show up instead of what you want!</li>
<li><b>script:</b> These scripts make your life a whole lot easier. The server script launches the development web server, and generate generates code.</li>
<li><b>test:</b> The tests you write and the ones Rails creates for you are all stored here.</li>
<li><b>tmp:</b> Rails stores any temporary files here.</li>
<li><b>vendor:</b> Here you can install any Rails plugins (or libraries) made by third-parties that do not come default with the Rails distribution.</li>
</ul>
<h3>Step 3 &#8211; Getting your Hands Dirty</h3>
<p>While the purpose of this tutorial is not to create an application, we will still do a bit of programming. Let&#8217;s first create a controller named articles: (Make sure you have changed into the root of the Rails application)</p>
<pre name="code" class="html">script/generate controller articles</pre>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/299_ror/5.jpg" border="0" /></div>
<p>Now open up the file, and you should see this:</p>
<pre name="code" language="php">class ArticlesController &lt; ApplicationController
end
</pre>
<p>All this code says is that we are defining a new class called ArticlesController that inherits from another class called ApplicationController. Now, we are going to create an action (referred to as a method strictly speaking in Ruby) name index, so when you go to http://localhost:3000/articles/ you will be shown something. Change your code so it looks like:</p>
<pre name="code" language="php">class ArticlesController &lt; ApplicationController
	def index
	end
end</pre>
<p>So now that we have an action, go to the app/views folder. We are going to create a view so when a user requests that URL, they actually see something. You may have noticed that there is a new folder in here named articles; this folder was created when we generated the controller. So, make a new file in the articles folder named index.html.erb. You may ask about the ending, the html refers to the type of file, and the erb refers to embedded Ruby as the templating engine. I personally prefer rhtml as it is a single ending, but that will be depreciated in Rails 3, which is planned to be released at RailsConf this summer. Put this into your new file:</p>
<pre name="code" language="php">

The time now is &lt;%= Time.now %>
</pre>
<p>The &#038;lt%= %> tags may intrigue you. This tag is meant so that Ruby ouputs the results of the enclosed Ruby code. So this code will print the Time now. The other tag you will use in Rails is simply &lt;%- -%>. This tag is meant for Ruby code that doesn&#8217;t actually output anything, such as when repeating through items in an array.</p>
<p>Now we are going to create a layout to make this text beautiful. So create a file in the views/layouts directory named application.html.erb with the following in it:</p>
<pre name="code" language="html">&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
&lt;html>
  &lt;head>
    &lt;title>&lt;%= h(@title) %>&lt;/title>
    &lt;%= stylesheet_link_tag 'application' %>
	&lt;%= javascript_include_tag 'prototype' %>
    &lt;%= yield(:head) %>
  &lt;/head>
  &lt;body>
    &lt;div id="container">
      &lt;%- flash.each do |name, msg| -%>
        &lt;%= content_tag :div, msg, :id => "flash_#{name}" %>
      &lt;%- end -%>
      &lt;%= yield %>
    &lt;/div>
  &lt;/body>
&lt;/html>
</pre>
<p>First, before I explain the code, I do want you to know why we named the file application.html.erb. Rails will automatically load this layout every time unless otherwise specified. If you had named this layout &#8220;layout&#8221; then you would have had to add <span style="font-family: Courier, Monaco, monospace; font-size: 12px; padding: 0; margin: 0; display:inline;">layout :layout</span> to the top of the controller. This block of code has some important tidbits that you will want to know for when you are developing layouts.</p>
<ul>
<li><b>&lt;%= stylesheet_link_tag &#8216;application&#8217; %>:</b> This tag generate the CSS inclusion tag for the CSS file named application.css</li>
<li><b>&lt;%= javascript_include_tag &#8216;prototype&#8217; %>:</b> This tag generates the Javascript inclusion tag for the Prototype javascript library. Prototype is the default javascript library that comes with Rails. You can also put :defaults (not in single quotes) instead of just prototype and Rails will load all of the defaults, :all would load all files in the public/javascripts folder.</li>
<li><b>&lt;%- flash.each do |name, msg| -%>:</b> This code and the code in the block means that for every item in the flash array, it will show a message to the the user.</li>
<li><b> &lt;%= yield %>:</b> This outputs all of the info from the individual view, and outputs in inside the template and sends this to the user.</li>
</ul>
<p>Now, let&#8217;s create a quick CSS file, named application.css in public/stylesheets, and put the following in it:</p>
<pre name="code" language="css">body {
  background-color: #111;
  font-family: Verdana, Helvetica, Arial;
  font-size: 14px;
}
#container {
  width: 75%;
  margin: 0 auto;
  background-color: #FFF;
  padding: 10px;
  border: solid 5px #999;
  margin-top: 20px;
}</pre>
<p>Now, we have a very simple application for displaying the current time; hopefully, you should be more acquainted with the basics of Rails.</p>
<h3>Step 4 &#8211; Finishing Up</h3>
<p>You might be thinking, &#8220;This is cool and all, but how do I see the final product?&#8221; There is a terminal command that you need to run while in the base of the Rails application to start the local development server. <span style="font-family: Courier, Monaco, monospace; font-size: 12px; padding: 0; margin: 0; display:inline;">script/server</span> will start the server, normally on port 3000. Run the command and point your browser to http://127.0.0.1:3000/articles. You should see the following:</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/299_ror/6.jpg" border="0" /></div>
<p>To stop the server select the terminal window and Control-C. This will stop the development server. As a note, make sure you never run a production server this way.</p>
<p>There is one last thing that I would like to show you. As I said before, the config/routes.rb file manages where requests go. Open up the file; we are going to make it so when you go to http://127.0.0.1:3000/, you see the same thing as before. Find the line, &#8220;# You can have the root of your site routed with map.root &#8212; just remember to delete public/index.html.&#8221; Under that section, add the following:</p>
<pre name="code" language="php">map.root :controller => "articles"</pre>
<p>Save the file, and make sure you restart the web server. You will always need to restart the server whenever you create a new model, and change some other files that Rails stores in memory to speed up the server. Make sure you delete public/index.html, or just rename it. Now make sure the server is started and go to http://127.0.0.1:3000. You should see the same thing.</p>
<h3>Conclusion</h3>
<p>So now you should be a little more familiar with Ruby on Rails. I have also linked to some really great sites to refer to when developing with Rails. Have fun coding with Rails!</p>
<ul>
<li><a href="http://railscats.com">Railscasts</a> put on by Ryan Bates is an amazing source of video tutorials, and you can always expect something great.</li>
<li>The <a href="http://api.rubyonrails.org/">Rails API</a> is a great way to find more information about a subject you may not be entirely sure about.</li>
<li><a href=""</li>
</ul>
<p>Follow us on <a href="http://www.twitter.com/nettuts">Twitter</a> for more daily web development tuts and articles.</p>
<p>
<script type="text/javascript"><!--digg_url = "post permalink (not digg url)"; // -->
</script><br />
<script src="http://digg.com/tools/diggthis.js" type="text/javascript"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://net.tutsplus.com/tutorials/ruby/ruby-on-rails-for-designers/feed/</wfw:commentRss>
		<slash:comments>86</slash:comments>
		</item>
		<item>
		<title>Ruby on Rails from Scratch Week 3</title>
		<link>http://net.tutsplus.com/tutorials/ruby/ruby-on-rails-from-scratch-week-3/</link>
		<comments>http://net.tutsplus.com/tutorials/ruby/ruby-on-rails-from-scratch-week-3/#comments</comments>
		<pubDate>Fri, 26 Sep 2008 12:00:12 +0000</pubDate>
		<dc:creator>Connor Zwick</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[ruby on rails]]></category>

		<guid isPermaLink="false">http://nettuts.com/?p=959</guid>
		<description><![CDATA[<img src="http://nettuts.s3.amazonaws.com/057_rubyOnRailsFromScratch/200x200.png" alt="Ruby On Rails: Week 3" />]]></description>
			<content:encoded><![CDATA[<p><em>Welcome to Ruby on Rails From Scratch Week 3! This week, we&#8217;ll focus on specific things that you need to know about the framework. For example, we&#8217;re going to talk about manipulating the structure of the project in two ways (rendering &amp; redirecting). We&#8217;ll also talk about how you add links in rails, and how to comment code. </em>Let&#8217;s get started already!</p>
<p><span id="more-959"></span></p>
<h3>Catching Up</h3>
<p>
If you haven&#8217;t read Parts 1 and 2, it is strongly advised that you review them before continuing on with this tutorial.
</p>
<ul>
<li><a href="http://nettuts.com/misc/learn-ruby-on-rails-from-scratch-week-1">Week One</a></li>
<li><a href="http://nettuts.com/site-builds/ruby-on-rails-from-scratch-week-2/">Week Two</a></li>
</ul>
<h2>Adding Interactions Amongst Actions</h2>
<p>Now that we&#8217;ve learned how to set instance variables to transfer information from the controller to the view, it is time to learn how to transmit data between different actions in a controller. For this tutorial, we&#8217;re going to continue using the learn controller. We don&#8217;t really need to keep what we did last week, but you can if you feel like it is a good resource.<a href="http://nettuts.com/misc/learn-ruby-on-rails-from-scratch-week-1"></a>. We&#8217;ll start off simple:</p>
<h3>Perform Another Action in a different Action</h3>
<p>For this example, the heading is more complex than the actual lesson. We are going to simply use what&#8217;s in one action and do the same in another. Lets use the knowledge we gained last week about instance variables, and apply it now. First, let&#8217;s create a new action called &quot;another_action&quot;; then another action called &quot;text&quot;. We are going to then get the action from text and put it in &quot;another_action&quot;. We are going to prove this, by referencing an instance variable in the view of &quot;another_action&quot; that was assigned in the &quot;text&quot; controller. Sorry, if that didn&#8217;t make sense. If you didn&#8217;t get what I just said, look at the following code, which will hopefully help you:</p>
<pre name="code" class="ruby">
class LearnController &lt; ApplicationController

  def another_action
  	text
  end

  def text
  	@text = 'This text came from another action'
  end
  end
</pre>
<p>We are then going to create a view called &quot;another_action.html.erb&quot;, where we reference the variable text. </p>
<pre name="code" class="html">&lt;html&gt;
  &lt;head&gt;
  &lt;title&gt;Action Demo&lt;/title&gt;
  &lt;/head&gt;
&lt;body&gt;

  &lt;%= @text %&gt;
  &lt;/body&gt;
  &lt;/html&gt;</pre>
<p><strong>Explanation</strong></p>
<p>As you can see, we referenced the action &quot;text&quot; simply by putting that inside of &quot;another_action&quot;. By doing this, we also passed the definition of &quot;text&quot;, which was the instance variable. To further demonstrate this principle, let&#8217;s put this in several different situations, all of which work. </p>
<h3>Situation 1- Setting An Instance Variable Equal to an Action</h3>
<pre name="code" class="ruby">
class LearnController &lt; ApplicationController

	def another_action
		@text = text
	end

	def text
		misc_text = 'This text really traveled!'
	end
end
</pre>
<h3>Situation 1 Result</h3>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/080_rubyWeek3/images/1.png" alt="Text Travelled" /></div>
<h3>Situation 2 &#8211; Replace Variable</h3>
<p>Now we&#8217;re going to get even more complex:</p>
<pre name="code" class="ruby">&lt;html&gt;
class LearnController &lt; ApplicationController

	def another_action
		@text = "text you'll never see"
		@text = text
	end

	def text
		wanted_text = overwrite_view
	end

	def overwrite_view
		overwrite_text = 'This text overwrote the original text'
	end
end
</pre>
<h3 name="code" class="ruby">Situation 2 Result</h3>
<p name="code" class="ruby">This is the order of events that the following code did:</p>
<ul>
<li>Gave the instance variable &quot;text&quot; a value of &quot;text you&#8217;ll never see&quot;</li>
<li>Then it re-assigned it to the action &quot;text&quot;</li>
<li>The variable &quot;text&quot;, now has the value of the local variable wanted text.</li>
<li>The wanted_text variable has a value of the action &quot;overwrite_view&quot;</li>
<li>Overwrite_view has a local variable with a value of &quot;This text overwrote the original text&quot;</li>
<li>This carries back to the instance variable of @text. </li>
</ul>
<div class="tutorial_image">
<img src="http://nettuts.s3.amazonaws.com/080_rubyWeek3/images/2.png" alt="" /></div>
<h3>Situation 3 Carry a Variable</h3>
<p >We&#8217;ll keep this one simpler:</p>
<pre name="code" class="ruby">class LearnController &lt; ApplicationController

	def another_action
		@text = "text you'll never see"
		text
	end

	def text
		@text = 'This text overwrote the original text'
	end
end</pre>
<h3 name="code" class="ruby">
Situation 3 Result</h3>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/080_rubyWeek3/images/2.png" alt="pass the variable" /></div>
<h3>Situation 4 Returning Something Specific</h3>
<pre name="code" class="ruby">class LearnController &lt; ApplicationController

	def another_action
		@text = text
	end

	def text
		first = 'This text should not be passed to @text'
		second = 'This text would be put into the variable on default'
		return first
	end

end
</pre>
<p>This example is particularly important, as you are now learning a little bit more syntax; the <strong>return</strong> command. This will tell the action what to return at the end. </p>
<h3>Situation 4 Result </h3>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/080_rubyWeek3/images/3.png" alt="return" /></div>
<h2>Rails Links</h2>
<p>Everyone should already know how to create a normal HTML link. (Using &lt;a href=&quot;&quot;&gt;Text&lt;/a&gt;) But there&#8217;s also a way to do it with Rails. This method is not Ruby, but rather a part of the framework. That being said, you can only use it in embedded ruby HTML files, not pure rb files. So how do we do it? Here is the code:</p>
<pre name="code" class="rails">&lt;html&gt;
  &lt;head&gt;
  &lt;title&gt;Rails Link Demo&lt;/title&gt;
  &lt;/head&gt;
&lt;body&gt;

  &lt;%= link_to('Another Action Link', :controller =&gt; 'learn', :action =&gt; 'another_action')%&gt;
  &lt;/body&gt;
  &lt;/html&gt;
</pre>
<p >At first glance, you might wonder why you would ever change the way you write links, especially if the replacement is longer! Well one main reason is readability. You can easily read this and know exactly what it&#8217;s going to link to. As for length, the :controller =&gt; part is not necessary if you&#8217;re linking to an action within the same controller. </p>
<p >With this piece of rails code we are also seeing symbols. The &quot;:controller =&gt;&quot; is a symbol. We&#8217;ll talk more about what they do later, but for right now just recognize the colon. </p>
<h2 >Rendering in Rails</h2>
<p >Earlier in this series, we talked a little bit about rails&#8217; sensible defaults. One of the defaults is to generate a view that has the same name as the action in the corresponding view. But what if we wanted to overwrite what rails automatically does? This is actually quite easy, and a very useful technique. When you&#8217;re working on a real world project, you can imagine how &#8216;clunky&#8217; your controller would get if you needed to create a separate view and action in the controller for each page. Rails has a solution though, which is called rendering. <strong>Rendering</strong> allows you to specify what view to use for each action. Keep in mind though, that like rails links, this is also rails exclusive code and not ruby, and meant only for the controller. </p>
<p >If the above has left you a little confused, let me show you how to do it. This will hopefully clarify it a little bit. For this first example, we&#8217;re going to render the action to the view that it would normally render anyway. In other terms, this render code does nothing that wouldn&#8217;t happen without it. All it is doing is showing some code that usually is just &#8216;assumed&#8217;.</p>
<pre name="code" class="rails">
	def index
		render :action =&gt; 'index'
	end
    </pre>
<h3 >Rendering an Action to another View</h3>
<p >The last example isn&#8217;t really useful since the result is achieved automatically anyway. But what if you had a really advanced view for another action, and you wanted the same view for a different action. It would not only be tedious to create another identical view for each action you create, but it would also be nearly impossible to update! All of that can be fixed though by rendering every similar action to a specific action. Examine the following piece of code which I will explain afterwards, and notice the different parts.</p>
<p ><strong>text_controller.rb:</strong></p>
<pre name="code" class="rails">
class LearnController &lt; ApplicationController

	def index
		render :action => 'text'
	end

	def text
		@text = '&lt;u>Text&lt;/u>'
	end

	def other
		@text = '&lt;b>Other&lt;/b>'
		render :action => 'text'
	end

end
</pre>
<p ><strong>text.html.erb:</strong></p>
<pre name="code" class="rails">
&lt;html&gt;
  &lt;head&gt;
  &lt;title&gt;Rails Rendering Demo&lt;/title&gt;
  &lt;/head&gt;

&lt;body&gt;

  &lt;p&gt;Welcome to the &lt;%= @text %&gt; Page&lt;/p&gt;


&lt;/body&gt;
  &lt;/html&gt;
</pre>
<h2 >Explanation of Code:</h2>
<p ><strong>Index Action</strong></p>
<p >You might have noticed that I included an action called &quot;index&quot;. This action will be viewed if you go up a directory to &quot;learn&quot;. It works like an ordinary index file would. You don&#8217;t have to create a specific action for index though. You can use the previously covered topic of inheriting another action as well.</p>
<p ><strong>Rendering to the same view</strong></p>
<p >For this example, we only needed one view for all of the actions; and they all produced different pages. To me, this is pretty incredible for the amount of work we put in. </p>
<p >Note: This might seem obvious to some, but beware of double rendering. Double rendering will cause an error because you&#8217;re trying to render an action to two different places. Can you be in two places at once? No, and neither can an action. If you want to see what it looks like, just render an action to two different views. The reason it happens as you&#8217;re doing more complex projects is because the trail of actions can get pretty complex, and you might accidentally create this error. </p>
<p >Make sure you get the basic concept of rendering, as it will be a very vital technique that you will use often as a rails developer. </p>
<h2 >Redirecting An Action</h2>
<p >Redirecting an Action is similar to rendering an action in the fact that it too is rails code and only used in the controller. Also, it effects the flow of the application. As you might guess from the name, redirecting allows you to&#8230; well redirect.</p>
<p >You might be surprised by how many times you use the redirect command. Here are some common uses:</p>
<ul>
<li>Creating alias pages</li>
<li>Performing an action in the controller and then redirecting to a secondary page</li>
<li>If there is an error, redirect to an error page</li>
<li>If user is not logged in, send them to a login page </li>
</ul>
<p>Enough chit chat, let&#8217;s get to the code! For this code example, we&#8217;re just going to modify the last example&#8217;s controller and leave the view the same. As you&#8217;ll see, redirecting is very similar in format to rendering:</p>
<pre name="code" class="rails">
class LearnController &lt; ApplicationController

	def index
		redirect_to :action => 'text'
	end

	def text
		@text = '&lt;u>Text&lt;/u>'
		redirect_to :action => 'other'
	end

	def other
		render :action => 'text'
	end

end
</pre>
<p>Now go to the index action in your browser. You&#8217;ll notice that you end up at the other action in your address bar. Let&#8217;s run through this code:</p>
<ul>
<li>First, we redirect to the action text. Like linking in rails, you can specify a controller too if you&#8217;re redirecting to another controller. You would just put :controller =&gt; &#8216;learn&#8217;, before the action. </li>
<li>The browser now goes to the text action. Here it sets a value for @text. But the browser has no value for @text. This is because redirecting essentially forgets anything you tell it in that action. </li>
<li>We are now redirected to other. Here we render out to the text view. </li>
</ul>
<h2>Render or Redirect?</h2>
<p>While there are some obvious scenarios where you would chose either to render or to redirect; there can be some harder decisions. One important key though is that if you&#8217;re submitting data into a database or anything that is changing the application, use a redirect. Otherwise, a refresh could resubmit the data. </p>
<h2>Final Thoughts</h2>
<p>Hope you guys learned a lot from this week&#8217;s tutorial! We covered a lot of important concepts so if you are still confused by anything, re-read it. Next week we&#8217;ll probably get into ruby syntax! </p>
<p>As always, feel free to leave questions in the comments. <strong>Also, please digg this article if it helped you!</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://net.tutsplus.com/tutorials/ruby/ruby-on-rails-from-scratch-week-3/feed/</wfw:commentRss>
		<slash:comments>44</slash:comments>
		</item>
		<item>
		<title>Learn Ruby on Rails from Scratch: Week 2</title>
		<link>http://net.tutsplus.com/tutorials/ruby/ruby-on-rails-from-scratch-week-2/</link>
		<comments>http://net.tutsplus.com/tutorials/ruby/ruby-on-rails-from-scratch-week-2/#comments</comments>
		<pubDate>Mon, 08 Sep 2008 12:00:51 +0000</pubDate>
		<dc:creator>Connor Zwick</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[ruby on rails]]></category>

		<guid isPermaLink="false">http://nettuts.com/?p=714</guid>
		<description><![CDATA[<img src="http://nettuts.s3.amazonaws.com/057_rubyOnRailsFromScratch/200x200.png" alt="Ruby On Rails From Scratch: Week 2" />]]></description>
			<content:encoded><![CDATA[<p><em>Welcome to Ruby on Rails From Scratch Week 2. Hopefully this sequel to<a href="http://nettuts.com/misc/learn-ruby-on-rails-from-scratch-week-1/"> week 1</a> will help to further your education in Rails. This week, we&#8217;ll do a little bit more with getting an actual page up and running. We&#8217;ll also work on adding more interactivity by embedding ruby in HTML and learning a little about variables. After that, we&#8217;ll learn more about Ruby&#8217;s beautiful URL structure and how to manipulate it, plus other things as well. This is definitely going to be a packed week!</em></p>
<p><span id="more-714"></span></p>
<h2>Last Week&#8230;</h2>
<p>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. </p>
<h2>Ruby Editors</h2>
<p>Now that we&#8217;re going to get into Rails Syntax, we need a good editor. Since rails is a relatively new framework, it doesn&#8217;t have quite the range of syntax supported editors. Luckily, there are still extremely good ones out there. For windows, I personally use <a href="http://www.e-texteditor.com/">E Texteditor</a>. 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 <a href="http://macromates.com/">TextMate</a>. The only downside to both, are that they aren&#8217;t free. If you&#8217;re looking for something free, you could always go with the reliable <a href="http://notepad-plus.sourceforge.net/uk/site.htm">Notepad ++</a>.</p>
<h2>Getting Things Visible</h2>
<h3>Creating an Action</h3>
<p>As you might remember from last week, we ended by creating a controller which we called <strong>learn</strong>. This will lead us into today&#8217;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 <strong>embedded ruby file (rhtml)</strong>. </p>
<p>Now that we have the learn controller generated, we can view the rb file by going to <em>app/controllers/learn_controller.rb</em>. Right now, you should see the following code already there:</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/067_RubyPart2/images/learn_controller_start.PNG" alt="controller start" /></div>
<p><em>This default code allows this controller to inherit the default application controls. </em></p>
<p>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 <strong>more</strong>, we type the following code:</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/067_RubyPart2/images/def_more.PNG" alt="def view" /></div>
<p>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 &quot;more&quot; page, you would type in, localhost:3000/learn/more. In fact, let&#8217;s try it and see what happens:</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/067_RubyPart2/images/missingtemplate.PNG" alt="missing template" /></div>
<p>Oops&#8230;as you can see from the helpful error message, we still need to make a view. </p>
<h3>Creating a View</h3>
<p>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. </p>
<p>A picture&#8217;s worth a thousand words, so here you go:</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/067_RubyPart2/images/learn view.PNG" alt="view more" /></div>
<p>And now, just to test out the page, we&#8217;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&#8217;d like here. </p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/067_RubyPart2/images/HTML skeleton.PNG" alt="HTML skeleton" /></div>
<p>Save it, and lets test it out again.</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/067_RubyPart2/images/test.PNG" alt="test" /></div>
<p>Great it works! Congratulations, you created your first page in Rails. Although it&#8217;s not much now, you now have a basic understanding of how to create a basic rails application.</p>
<h3>A Note</h3>
<p>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&#8217;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&#8217;t want to do the same to you! But, if I explained them all now, it wouldn&#8217;t sink in as well, as if you knew more about each component. So don&#8217;t worry about it too much now, and I&#8217;ll explain it later in this series.</p>
<h2>Adding Interactivity </h2>
<p><strong>Review</strong></p>
<p>Last week, we learned how to embed rails code into an rhtml file. If you remember, a &lt;% -%&gt; is processed code, but doesn&#8217;t include anything that will actually be outputted to the user. On the other hand, &lt;%= %&gt; code will be outputted. </p>
<p><strong>Math Time</strong></p>
<p>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>
<pre name="code" class="rails">

&lt;html&gt;
  &lt;head&gt;
  &lt;title&gt;Math Demo&lt;/title&gt;
  &lt;/head&gt;
&lt;body&gt;
  Will it output 4 +5, or 9?&lt;br /&#038;gt
  &lt;%= 4 +5 %&gt;
  &lt;/body&gt;
  &lt;/html&gt;

</pre>
<p>As you can see, it did the math for us:</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/067_RubyPart2/images/math.PNG" alt="math" /></div>
<p><strong>String Concatenation</strong></p>
<p>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:</p>
<pre name="code" class="rails">
&lt;html&gt;
  &lt;head&gt;
  &lt;title&gt;String Demo&lt;/title&gt;
  &lt;/head&gt;
&lt;body&gt;

  &lt;%= 'This is kind of boring' %&gt;&lt;br&gt;
  &lt;%= 'Will I combine' + 'With You?' %&gt;
  &lt;/body&gt;
  &lt;/html&gt;
</pre>
<p>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.</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/067_RubyPart2/images/helloworld.PNG" alt="hello world" /></div>
<h2><strong>How Important is the = and &#8211; sign?</strong></h2>
<p>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&#8217;t physically output anything, then don&#8217;t put the = sign,</p>
<p>The &#8211; sign is not necessary, but a good habit to get into. If you&#8217;re not using the = sign, then put a &#8211; sign, when you&#8217;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. </p>
<h2>Variables</h2>
<p>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. </p>
<p><strong>Assigning A Local Variable and Displaying It</strong></p>
<p>Assigning a<strong> local variable</strong> is quite easy. Here is how you would assign it and then display it. You could do this in one line, but I&#8217;m showing the difference between embedded processed ruby and embedded and shown ruby (The equal sign thing again <img src='http://net.tutsplus.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  ):</p>
<pre name="code" class="rails">
&lt;html&gt;
  &lt;head&gt;
  &lt;title&gt;Variable Demo&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;

  &lt;% text = 'This is a Variable' -%&gt;
  &lt;i&gt;&lt;%= text %&gt;&lt;/i&gt;
  &lt;/body&gt;
  &lt;/html&gt;</pre>
<p>And here you can see the result:</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/067_RubyPart2/images/variables.PNG" alt="variables" /></div>
<p><strong>Assigning An Instance Variable and Displaying It</strong></p>
<p>The problem with local variables, though, is that they&#8217;re&#8230;local. What if we need to assign a variable in the controller, and display it in the view? That&#8217;s where <strong>instance variables </strong>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. </p>
<p>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):</p>
<pre name="code" class="ruby">
class LearnController &lt; ApplicationController

	def more
	end

	def math
	end

	def strings
	end

	def variables
		@text = 'Why Hello'
	end

end</pre>
<p>Now we&#8217;re going to reference the variable in the view:</p>
<pre name="code" class="rails">
&lt;html&gt;
  &lt;head&gt;
  &lt;title&gt;Variable Demo&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
      &lt;i&gt;&lt;%= @text %&gt;&lt;/i&gt;
  &lt;/body&gt;
  &lt;/html&gt;</pre>
<p>Sure enough, the variable is passed to the view. </p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/067_RubyPart2/images/instance variable.PNG" alt="variables" /></div>
<p>&nbsp;</p>
<h2>Next Week and Final Words</h2>
<p>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&#8217;ll be sure to get back to you!</p>
<p>Like always, please Digg this if it helped you!</p>
<ul class="webroundup">
<li>Subscribe to the <a href="http://feeds.feedburner.com/nettuts" title="NETTUTS RSS Feed">NETTUTS RSS Feed</a> for more daily web development tuts and articles.</li>
</ul>
<p>
<script type="text/javascript"><!--digg_url = "post permalink (not digg url)"; // -->
</script><br />
<script src="http://digg.com/tools/diggthis.js" type="text/javascript"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://net.tutsplus.com/tutorials/ruby/ruby-on-rails-from-scratch-week-2/feed/</wfw:commentRss>
		<slash:comments>67</slash:comments>
		</item>
		<item>
		<title>Learn Ruby on Rails from Scratch: Week 1</title>
		<link>http://net.tutsplus.com/tutorials/ruby/learn-ruby-on-rails-from-scratch-week-1/</link>
		<comments>http://net.tutsplus.com/tutorials/ruby/learn-ruby-on-rails-from-scratch-week-1/#comments</comments>
		<pubDate>Thu, 28 Aug 2008 12:00:04 +0000</pubDate>
		<dc:creator>Connor Zwick</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[ruby on rails]]></category>

		<guid isPermaLink="false">http://nettuts.com/?p=570</guid>
		<description><![CDATA[<img src="http://nettuts.s3.amazonaws.com/057_rubyOnRailsFromScratch/200x200.png" alt="Ruby On Rails" />]]></description>
			<content:encoded><![CDATA[<p><em>Ruby  on Rails. . .by now most people have heard the hype about it. It promises more  effective code, total object orientation, and true MVC architecture to say the  least. As far as my own personal experience, it has been all that and more. The  code is beautiful, easy to maintain, and edit. In a recent project I was working on, it took me less than 10 hours to do the application, as compared to  at least double that if I was writing in PHP. </em></p>
<p><span id="more-570"></span></p>
<p>I&#8217;ve heard a lot of web developers that know  other languages, usually ASP or PHP, that want to learn Ruby on Rails, but just don&#8217;t know  where to get started. From personal experience, I know it is very different  from PHP. Personally, I learned Ruby on Rails less than a year ago, and have  had few to no problems with it so far. If you haven&#8217;t already, I highly recommend  hopping on board with the up and coming web framework, Ruby on Rails!</p>
<h2>Mission Statement </h2>
<p>In this series of  tutorials, I hope to take you from knowing nothing about Ruby on Rails (if  that&#8217;s true), to being able to write fully featured web applications in  it. I remember what it was like to learn  it. I couldn&#8217;t find any series of tutorials that took you through all of the  essentials in plain English and in an order that was benefiticial to me, the learner. Although there are very good resources out there, they need to be combined with others as well. At the bottom of this tutorial, I&#8217;m also going to list resources that I have found useful in the past as well. </p>
<p>This series will be similar to the PHP from scratch series, but with Ruby on Rails.There will be one published every week, gradually getting more advanced. </p>
<h2>This Tutorial</h2>
<p>I warn you, this  first tutorial might be a little dry, but it&#8217;s necessary for learning RoR  (let&#8217;s just call it that from now on!). This week, we&#8217;re going to cover setting  up the framework and web server as well as how the framework works. We&#8217;re going  to set the necessary foundation for learning RoR. This is where many web  developers that want to learn RoR fail.I promise we will be doing much much  more exciting things next time!</p>
<h2>What is Ruby?</h2>
<p>Ruby is the language  that the framework rails extends. It is very object orientated. It&#8217;s syntax is  inspired by Perl&#8217;s, and therefore is very similar. It is also similar to  Python, Lisp, Dylan, and CLU. To quote <a href="http://en.wikipedia.org/wiki/Ruby_%28programming_language%29">Wikipedia</a>:</p>
<p> &quot;Ruby was conceived on February 24, 1993  by Yukihiro Matsumoto who wished to create a new language that balanced  functional programming with imperative programming.According to Matsumoto he  &#8216;wanted a scripting language that was more powerful than Perl, and more  object-oriented than Python.That&#8217;s why I decided to design my own  language&#8217;. &quot;</p>
<p>It was most popular  in Japan, that is until the framework Rails came out. Ever since, it has  continued to grow at a phenomenal rate everywhere. </p>
<h2>What is Rails?</h2>
<p>Rails is the famous  framework that works off of ruby. It&#8217;s user base is constantly growing. Developed by David Heinemeier Hansson of 37signals for basecamp, it was  released as open source in July 2004. It uses MVC (Model &#8211; View &#8211; Controller ) architecture. If  you want a brush up on MVC, be sure to check out the MVC tutorial. The latest  release is 2.1.0. There were some significant changes in the v2. This includes  the famous scaffolding feature of v1. It&#8217;s changed a little bit in version 2. </p>
<h2>Concepts of Ruby on  Rails </h2>
<p>Ruby on Rails  follows several principles to help keep it&#8217;s code sleek and clean. You should  try to live by these principles while you&#8217;re working with RoR to get the most  of it. For one, it follows the Agile programming term of <strong>DRY (Don&#8217;t repeat yourself)</strong>. Obviously, this means that you only  write your code once in a certain consistent place. For example, if you need  the code to do a certain thing, then you&#8217;ll put it in a certain place every  time. </p>
<p>The second concept  that RoR follows is <strong>CoC (Conventions over  Configuration)</strong>.This pretty much  means that ruby assumes a lot, and explains most of the automatic defaults you&#8217;ll see ruby generate for us. Instead of you always having to configure  everything, in every single project, ruby does it for you automatically.Then,  if you want to do something that&#8217;s unconventional, you simply override the sensible defaults that RoR already has in  place.This generally leads to less code having to be written. </p>
<p><strong>Advantages of Learning Ruby on Rails:</strong></p>
<ul>
<li>It is pretty easy to learn compared to other languages</li>
<li>Completely Object Orientated </li>
<li>MVC Architecture</li>
<li>You don&#8217;t have to write as much code</li>
<li>Very extendible </li>
<li>Open Source</li>
<li>The community is extremely helpful in answering questions</li>
<li>Despite being a relatively new framework, it is pretty fully featured, and has very few bugs.</li>
</ul>
<p><strong>Disadvantages of Ruby</strong>:</p>
<ul>
<li>Processed different, so the code can be a little bit slower on servers that aren&#8217;t really built to handle ruby code</li>
</ul>
<p>I&#8217;ve only heard this claim, but more and more servers are becoming better equipped for Rails as it continues to grow anyway so it&#8217;s becoming less and less of a problem. </p>
<h2>A Ruby File</h2>
<p>A ruby file has the extension of .rb. These files will usually contain no HTML. This is an excerpt of a ruby file (specifically a controller) from a game engine I recently made. As you might be able to see. It pulls data from a database, and lists games according to the variables category and title:
</p>
<pre name="code" class="ruby">class GameController &lt; ApplicationController

	def game_list		@title = '3'		@category = 'Action'		@games = Game.find(:all, 		:conditions =&gt; [&quot;title LIKE ? AND category = ?&quot;, '%' + title + '%', category],	 <img src='http://net.tutsplus.com/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> rder =&gt; 'title, category ASC',		:limit =&gt; 5, <img src='http://net.tutsplus.com/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> ffset =&gt; 0)	end

end
</pre>
<h2>An embedded Ruby File</h2>
<p>Like many other web languages, Rails allows you to embed ruby with HTML. Seki Masatoshi wrote a program called ERb, embedded ruby, which scans all .rhtml files (embedded ruby files), until it comes across either &lt;% Ruby Code that is only processed -%&gt; or &lt;%= Ruby Code that is then outputted %&gt;. It then processes the ruby code and fills in the blank if neccesary. </p>
<p>Here is an example of Embedded Ruby: </p>
<pre name="code" class="rails">&lt;% title = &quot;Nettuts&quot; %&gt;&lt;% header_text = &quot;Ruby on Rails Tutorial&quot; %&gt;&lt;html&gt;&lt;head&gt;&lt;title&gt;&lt;%= title %&gt;&lt;/title&gt;&lt;/head&gt;&lt;body&gt;&lt;h2&gt;&lt;%= header_text %&gt;&lt;/h2&gt;&lt;p&gt;This is an example of a .rhtml page. &lt;/p&gt;&lt;/body&gt;&lt;/html&gt;
</pre>
<p name="code" class="rails">This is how the user will get it:</p>
<pre name="code" class="rails">
&lt;html&gt;
  &lt;head&gt;
  &lt;title&gt; Nettuts &lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
  &lt;h2&gt;Ruby on Rails Tutorial&lt;/h2&gt;
  &lt;p&gt;This is an example of a .rhtml page. &lt;/p&gt;
  &lt;/body&gt;
  &lt;/html&gt; 
</pre>
<p>&nbsp;</p>
<h2>Installing Ruby on  Rails For Windows </h2>
<p>Windows and OSX  users are both very lucky. Both operating systems get an all-in-one installer/manager program that installs ruby, rails, and the server.For windows, you have the  option of Instant Rails. Go to <a href="http://instantrails.rubyforge.org/wiki/wiki.pl">http://instantrails.rubyforge.org/wiki/wiki.pl</a> to download it. I personally have used this, and have had no major problems  with it.Trust me, it is much easier to do this, then install everything  separately. </p>
<p><div class="tutorial_image">
<img src="http://nettuts.s3.amazonaws.com/057_rubyOnRailsFromScratch/images/instantrails.PNG" alt="Instant Rails">
</div>
</p>
<p>Click download to  get instantrails. </p>
<p>When you click download, you will be redirected to <a href="http://rubyforge.org/frs/?group_id=904">rubyforge.org</a>. There you can choose the latest version. At the time of this writing, 2.0 was the latest. Also at the time of this writing, a lot of popular hosts that supported ruby, only supported 1.8.x version. There are considerable differences between version 1 and 2. So it&#8217;s up to you which version you&#8217;d like to install. In this tutorial I&#8217;ll download version 2.0. </p>
<div class="tutorial_image">
<img src="http://nettuts.s3.amazonaws.com/057_rubyOnRailsFromScratch/images/instantrails_download.PNG" alt="Instant Rails Download" />
</div>
<p>Now that it&#8217;s downloaded, extract it to a directory that contains no spaces. </p>
<h2>Installing Ruby on  Rails For Other OS&#8217;s</h2>
<p>OSX also has the good fortune of having an all in one Ruby on Rails manager, locomotive. For OSX, and other Operating Systems, you can find a very good resource at Ruby on Rail&#8217;s <a href="http://wiki.rubyonrails.org/rails/pages/GettingStartedWithRails">wiki</a>.</p>
<p>&nbsp;</p>
<h2>Getting Started with the Framework</h2>
<p>From now on, I&#8217;m going to be using Instant Rails. It isn&#8217;t very different from any other set up so if you&#8217;re using another technique you should still be able to follow along easily. If you run into any problems, be sure to let me know in the comments and/or check out the resources. </p>
<p>So now that you have all of the files needed in place for your setup. Start it up! For windows, go to the directory you put Instant Rails, and run InstantRails.exe . You probably will get this message, but for your directory, which you can press &#8216;yes&#8217; for:</p>
<div class="tutorial_image">
<img src="http://nettuts.s3.amazonaws.com/057_rubyOnRailsFromScratch/images/instantrails_message.PNG" alt="Instant Rails Message"></div>
<p>Now that Instant Rails is running, you can do several things. Right now, you only need to able to:</p>
<p>- Open a console window</p>
<p>-Create a new project. </p>
<p>- Start the server for a current project</p>
<p>We&#8217;ll go through each action separately. </p>
<h3>Open up a console window</h3>
<p>1) Click on the upper left icon:</p>
<div class="tutorial_image">
<img src="http://nettuts.s3.amazonaws.com/057_rubyOnRailsFromScratch/images/instantrails_console.PNG" alt="Instant Rails UI"></div>
<p>2) Go to &quot;Rails Applications&quot; &gt; &quot;Open Ruby Console Window&quot; </p>
<p>3) We now have a console window open. Here you can do many things in ruby like generating new projects, controllers, and other tasks that we&#8217;ll cover later. Now we&#8217;re going to use this Console Window to create a new application. </p>
<h3>Creating A New Application</h3>
<p>1) Now we&#8217;re going to type in &quot;rails nettuts&quot;, where nettuts is the name of your application. Choose the name carefully, as you&#8217;ll be using it for the rest of the application. Since we&#8217;re not really doing anything particular yet, we&#8217;ll just choose nettuts as our name:</p>
<div class="tutorial_image">
<img src="http://nettuts.s3.amazonaws.com/057_rubyOnRailsFromScratch/images/console_rails_nettuts.PNG" alt="Console Create Nettuts"></div>
<p>2) It will now generate all of the necessary files for the application. These are the files that the framework uses and needs. It will help provide the <strong>CoC (Conventions over Configuration)</strong>. </p>
<div class="tutorial_image">
<img src="http://nettuts.s3.amazonaws.com/057_rubyOnRailsFromScratch/images/console_rails_generated.PNG" alt="Console Create Nettuts">
</div>
<p>3)We now have a Ruby on Rails application generated!</p>
<h3>Running an Application</h3>
<p>1) To run our application, we need to go to Instant Rails and click on the icon again:</p>
<p><img src="http://nettuts.s3.amazonaws.com/057_rubyOnRailsFromScratch/images/instantrails_console.PNG" alt="Instant Rails UI"></p>
<p>2) Then we&#8217;ll go to &quot;Rails Applications&quot; &gt; &quot;Manage Rails Applications&#8230;&quot;</p>
<div class="tutorial_image">
<img src="http://nettuts.s3.amazonaws.com/057_rubyOnRailsFromScratch/images/manage_applications.PNG" alt="Manage Applications"></p>
</div>
<p>2) You can see Instant Rails ships with two projets already. The cookbook is a pretty neat demo of what you can do easily with Rails. I highly encourage you to check it out. And then after you learn a little bit more about Rails check out the source code. You&#8217;ll be surprised at the simplicity! Anyway, check the box next to nettuts, and click &quot;Start with Mongrel&quot; . Your firewall might object, but allow it. A console window should pop-up with the port number and other useful information:</p>
<div class="tutorial_image">
<img src="http://nettuts.s3.amazonaws.com/057_rubyOnRailsFromScratch/images/server.PNG" alt="Manage Applications"></div>
<p>So in my case (and probably in yours too), we can view our application at port 3000. So just navigate to  127.0.0.1:3000, and you should get this default Rails page (plus the sidebar to the right):</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/057_rubyOnRailsFromScratch/images/application.PNG" alt="Manage Applications"></div>
<p>We can now start building our application!</p>
<h2>How the Framework Works</h2>
<h3>MVC Architecture</h3>
<p>Rails runs off of MVC Architecture. Basically that means we break up our code into three sections; the model, the view, and the controller. If you&#8217;d like to learn more about MVC Architecture be sure to visit the Nettuts <a href="http://nettuts.com">MVC</a> introduction tutorial. In this intro to Ruby on Rails, we&#8217;ll only cover the basics of the controller: </p>
<h3>The Controller</h3>
<p> The controller will be the path after the main url. For example, if we have a controller that is named &quot;learn&quot;, it would represent <em>yoursite.com/learn</em> or locally <em>127.0.0.1:3000/learn</em> . Each controller relies on many specific files, therefore to create a controller, you need to generate it via the console. We&#8217;re now going to create a new controller, learn:</p>
<p>1) First, we open up a console window via Instant Rails, or which ever setup you&#8217;re using. </p>
<p>2)Next we navigate to the current application. Since we are currently one level above our application, we type in &quot;cd nettuts&quot; (<em>change directory to nettuts</em>). </p>
<div class="tutorial_image">
<img src="http://nettuts.s3.amazonaws.com/057_rubyOnRailsFromScratch/images/console_navigate.PNG" alt="cd nettuts"></div>
<p>3)Now that we&#8217;re in the application, we need to access a script that will generate the controller. If you examine the file structure of the app, you&#8217;ll notice that there&#8217;s a script folder. And inside the script folder, there is a generate file. We need to target that, and run it. </p>
<div class="tutorial_image">
<img src="http://nettuts.s3.amazonaws.com/057_rubyOnRailsFromScratch/images/file_structure.PNG" alt="directory"></div>
<p>4) We&#8217;ll target it via the console. Notice the other scripts as well, they all have their purpose. Anyway, in windows type in &quot;ruby script/generate controller learn&quot; to generate a controller called learn. If I remember right, you don&#8217;t need the ruby in other Operating Systems. The console will now generate some files. Check these out in an explore window if you want. The two most important files here are the controller learn, which was just one of several files created; but notice also that a view called learn was also created. These are the <strong>sensible defaults </strong>that rails comes with to limit the amount of work involved. </p>
<div class="tutorial_image">
<img src="http://nettuts.s3.amazonaws.com/057_rubyOnRailsFromScratch/images/learn_controller.PNG" alt="Controllers"/></div>
<p><strong>So how does a controller work?</strong></p>
<p>Well let&#8217;s take it step by step. </p>
<p>-User requests yoursite.com/learn</p>
<p>-Rails automatically looks in the servers directory for app/learn_controller</p>
<p>-Rails scans the .rb file for an index file&#8217;s definition</p>
<p>-Rails does what the definition tells it to do, and eventually creates or redirects to a view.</p>
<p>-This view (learn), is then sent back to the user. </p>
<p>Don&#8217;t worry if this isn&#8217;t quite making sense. Next tutorial we will go in more depth into controllers. For right now, just be familiar with how to create a controller, and that they exist. </p>
<h2>Resources </h2>
<ul class="webroundup">
<li>
<div><img src="http://nettuts.s3.amazonaws.com/057_rubyOnRailsFromScratch/images/lynda.jpg" alt="Lynda.com"></div>
<h4>Lynda.com : Ruby on Rails Essential Training</h4>
<p>Ruby on Rails aims to make building web applications simpler. In <em>Ruby on Rails Essential Training</em>,  expert instructor Kevin Skoglund focuses on the same goal. Kevin  explains the complete process&#8211;from understanding the fundamental  concepts behind any Ruby on Rails project to creating full-featured,  easy-to-maintain applications using the Ruby on Rails framework.</p>
<p><a href="http://movielibrary.lynda.com/html/modPage.asp?ID=324">Visit Article</a></p>
</li>
<li>
<div>
   <img src="http://nettuts.s3.amazonaws.com/057_rubyOnRailsFromScratch/images/tutorialspoint.jpg" alt="Developer's Zone"></div>
<h4>Tutorial&#8217;s Point Ruby on Rails Series</h4>
<p>This is an incredible series of Ruby on Rails tutorial, which covers a lot, but it&#8217;s sometimes hard to follow.</p>
<p><a href="http://www.tutorialspoint.com/ruby-on-rails/">Visit Article</a></p>
</li>
<li>
<div><img src="http://nettuts.s3.amazonaws.com/057_rubyOnRailsFromScratch/images/rubyonrails.jpg" alt="Ruby on Rails"></div>
<h4>Ruby on Rails</h4>
<p>This is Rail&#8217;s official site. If you want to get excited about Rails, go here! Here you can download the newest version, get the latest news, and find some other resources for learning Rails. </p>
<p><a href="http://rubyonrails.com">Visit Article</a></p>
</li>
<li>
<div>
   <img src="http://nettuts.s3.amazonaws.com/057_rubyOnRailsFromScratch/images/railswiki.jpg" alt="PHP.NET"></div>
<h4>Rails Wiki</h4>
<p>This is another great resource. Once you become the next Rails ninja, you might even be compelled to edit some of the information here!</p>
<p><a href="http://wiki.rubyonrails.org/rails">Visit Article</a></p>
</li>
</ul>
<p>Be sure to check out as many of these resources before the next tutorial. </p>
<h2 style="clear: both;">Next Week and Final Words</h2>
<p>Well, I hope you were able to survive through all of that information. Trust me, you&#8217;ll be glad you did. Be sure you get the overall grasp of this tutorial. As we go on, most of your questions will be answered, and you will start feeling more &quot;enlightened&quot;, on what Rails is. And I promise next week will be more fun! Next week we will cover a little bit more of the framework, and start getting into ruby syntax, and a little more of what you can do with rails. If this tutorial helped you, please Digg it!</p>
<ul class="webroundup">
<li>Subscribe to the <a href="http://feeds.feedburner.com/nettuts" title="NETTUTS RSS Feed">NETTUTS RSS Feed</a> for more daily web development tuts and articles.</li>
</ul>
<p>
<script type="text/javascript"><!--digg_url = "post permalink (not digg url)"; // -->
</script><br />
<script src="http://digg.com/tools/diggthis.js" type="text/javascript"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://net.tutsplus.com/tutorials/ruby/learn-ruby-on-rails-from-scratch-week-1/feed/</wfw:commentRss>
		<slash:comments>105</slash:comments>
		</item>
	</channel>
</rss>
<!--
This site's performance optimized by W3 Total Cache:

W3 Total Cache improves the user experience of your blog by caching
frequent operations, reducing the weight of various files and providing
transparent content delivery network integration.

Learn more about our WordPress Plugins: http://www.w3-edge.com/wordpress-plugins/

Page Caching using memcached
Database Caching 6/19 queries in 0.007 seconds using memcached
Content Delivery Network via 

Served from: psdtutsplus.com @ 2009-11-21 15:32:43 -->