No Gravatar

Hello again! I’ve been quite busy in between jobs and haven’t had much free time to work on my postings…well, let’s make up for lost time! Last time we spoke, I left you with a Rails app that made use of a basic relational database that contained books and associated authors. Let’s move the chains and introduce a few new concepts that you’ll be able to use with your own applications.

In this installment we’re going to create a landing page so visitors don’t get dumped to your book controller, use a partial, learn about the before_filter, and add some basic HTTP authentication.

if/for blocks and Rails’ partials

The first thing we’re going to do is create a new landing page so visitors don’t get dumped onto the scaffolding, but first reset the database. I had some random entries there I wanted to wipe out, we can do this with:

ng:bookstore ng$ rake db:reset

Next, we’ll be generating a new controller to handle the requests for our landing page; following convetion this controller will be plural…call it “homes”.

ng:bookstore ng$ script/generate controller homes
      exists  app/controllers/
      exists  app/helpers/
      create  app/views/homes
      exists  test/functional/
      create  app/controllers/homes_controller.rb
      create  test/functional/homes_controller_test.rb
      create  app/helpers/homes_helper.rb
ng:bookstore ng$

If you try to access http://localhost:3000/homes you’ll get a routing error; know what to do? Bingo! Let’s add a resource to our route and change the default map.root controller. I’ve removed the comments, but your routes.rb file should look similar to this:

ActionController::Routing::Routes.draw do |map|
  map.resources :authors
  map.resources :books
  map.resources :homes 
 
  map.connect ':controller/:action/:id'
  map.connect ':controller/:action/:id.:format'
  map.root    :controller => 'homes'
end

Now that our routes are set up, we need to create an index.html.erb file. We’ll place this in the apps/views/homes directory. You will be able to access the homes controller by either of these urls:

  • http://localhost:3000/
  • http://localhost:3000/homes

Our index file is quite barren right now, let’s add some code to so we can list our current book inventory. First, we need data to play with! Open your apps/controllers/homes_controller.rb and add an index method. Let’s pull all records from our database and make it available to our view.

class HomesController < ApplicationController
 
  def index
    @books = Book.find(:all)
  end
 
end

Now that we’ve defined our data, we can loop through it using a basic for loop. I’ve set up the table structure with a header row, the individual rows are generated by our loop.

<table>
	<tr>
		<th>Title</th>
		<th>Description</th>
	</tr>
	<% for book in @books %>
	<tr>
		<td><%=h book.title %></td>
		<td><%=h book.description %></td>
	</tr>
	<% end %>
</table>

It essentially reads, “For each book in our @books collection, output a row with two columns. In in first column output an html escaped book title, in the second column output a html escaped book description. Once we’ve cycled through all the data in our @books collection, end the loop.”

I’m going to plug the above code into our index file.

<h1>Our Bookstore</h1>
 
<p>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Vivamus sed nisi. Morbi aliquam ornare metus. Aliquam sed pede quis nulla porta rhoncus. Ut adipiscing aliquam enim. Sed laoreet justo in turpis. Aenean metus lorem, mollis elementum, pulvinar non, pharetra at, metus. Phasellus interdum tortor non tellus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Integer facilisis, erat sed aliquam tristique, mi augue tristique mauris, in mollis turpis tellus vel sem. Vivamus ac nibh ac lectus venenatis blandit. Morbi eget sem ac turpis sodales tincidunt. In in nunc commodo ante venenatis ornare. Aliquam sit amet ligula.	
</p>
 
<h2>Current Inventory</h2>
<table>
	<tr>
		<th>Title</th>
		<th>Description</th>
	</tr>
	<% for book in @books %>
	<tr>
		<td><%=h book.title %></td>
		<td><%=h book.description %></td>
	</tr>
	<% end %>
</table>
 
 
<p>Aliquam vestibulum ultricies velit. Vivamus pulvinar urna. Mauris tincidunt blandit massa. </p>

Visit your bookstore. It looks kind of weird with no books eh? Let’s notify our visitors that we don’t have any books in stock; we’ll do this with a simple if statement.

<h1>Our Bookstore</h1>
 
<p>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Vivamus sed nisi. Morbi aliquam ornare metus. Aliquam sed pede quis nulla porta rhoncus. Ut adipiscing aliquam enim. Sed laoreet justo in turpis. Aenean metus lorem, mollis elementum, pulvinar non, pharetra at, metus. Phasellus interdum tortor non tellus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Integer facilisis, erat sed aliquam tristique, mi augue tristique mauris, in mollis turpis tellus vel sem. Vivamus ac nibh ac lectus venenatis blandit. Morbi eget sem ac turpis sodales tincidunt. In in nunc commodo ante venenatis ornare. Aliquam sit amet ligula.	
</p>
 
<% if @books.empty? %>
<h2>We don't have any books in stock, but they're coming!</h2>
<% else %>
<h2>Current Inventory</h2>
<table>
	<tr>
		<th>Title</th>
		<th>Description</th>
	</tr>
		<% for book in @books %>
		<tr>
			<td><%=h book.title %></td>
			<td><%=h book.description %></td>
		</tr>
		<% end %>
</table>
<% end %>
 
<p>Aliquam vestibulum ultricies velit. Vivamus pulvinar urna. Mauris tincidunt blandit massa. </p>

Pretty cool eh? It’s these little methods that make me smile! Let’s take another look at our index file…take a peek and ask yourself if anything looks out of place? Does that for loop bother you? It bothers me! I don’t like to see lots of code in my views…let’s get rid of it!

Rails has a handy feature called partials; partials are little fragments of code that can be included, and reused in your views. All partials take follow the same naming convention: “_filename.mimetype.erb”. Don’t worry about mimetypes right now, for the most part you’ll be something like _filename.html.erb or _filename.xml.erb. Create a new partial named named “book listings”, then place our if/for block in the partial.

<!-- _book_listings.html.erb -->
<% if @books.empty? %>
<h2>We don't have any books in stock, but they're coming!</h2>
<% else %>
<h2>Current Inventory</h2>
<table>
	<tr>
		<th>Title</th>
		<th>Description</th>
	</tr>
		<% for book in @books %>
		<tr>
			<td><%=h book.title %></td>
			<td><%=h book.description %></td>
		</tr>
		<% end %>
</table>
<% end %>

Now that we have a partial, we need to call it. render :partial => ‘partial_name’. Render the partial in our index view where our old if/for block was.

<!-- index.html.erb -->
<h1>Our Bookstore</h1>
 
<p>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Vivamus sed nisi. Morbi aliquam ornare metus. Aliquam sed pede quis nulla porta rhoncus. Ut adipiscing aliquam enim. Sed laoreet justo in turpis. Aenean metus lorem, mollis elementum, pulvinar non, pharetra at, metus. Phasellus interdum tortor non tellus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Integer facilisis, erat sed aliquam tristique, mi augue tristique mauris, in mollis turpis tellus vel sem. Vivamus ac nibh ac lectus venenatis blandit. Morbi eget sem ac turpis sodales tincidunt. In in nunc commodo ante venenatis ornare. Aliquam sit amet ligula.	
</p>
 
<%= render :partial => 'book_listings' %>
 
<p>Aliquam vestibulum ultricies velit. Vivamus pulvinar urna. Mauris tincidunt blandit massa. </p>

Rails’ before filter and basic HTTP authentication

Originally, I wanted to have us create a separate administrator section for administering the Books and Authors, but I think you’ll be able to do that on your own with the concepts we’ve worked on. Instead of a separate administrators section, let’s add some basic HTTP authentication to our Books and Authors controllers. By adding this authentication, we will be password protecting all calls to this controller. Here’s a snippet of code I use for basic access control:

def authenticate
  authenticate_or_request_with_http_basic do |user_name, password|
    user_name == "foo" && password == "bar"
  end
end

If we placed this method in our Books controller with the rest of our methods, anybody could call it by visiting books/authenticate; instead we’re going to place in a walled garden. Using Rails you have two options to protect your methods: private and protected. If you’re curious what they both do, here’s an an excerpt from RubyLearning:

  • Protected methods can be invoked only by objects of the defining class and its subclasses. Access is kept within the family. However, usage of protected is limited.
  • Private methods cannot be called with an explicit receiver - the receiver is always self. This means that private methods can be called only in the context of the current object; you cannot invoke another object’s private methods.

We’ll be using the protected method, we can do this by wrapping it like so:

class BooksController < ApplicationController  
  # note: I've truncated the methods after index
 
  before_filter :authenticate
 
  # GET /books
  # GET /books.xml
  def index
    @books = Book.find(:all)
 
    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @books }
    end
  end
 
protected
 
  def authenticate
    authenticate_or_request_with_http_basic do |user_name, password|
      user_name == "foo" && password == "bar"
    end
  end

You may have noticed before_filter :authenticate before all of our methods. This is part of the master plan! By adding a “before_filter” we’re asking Rails to call authenticate (which we’ve defined). As is, authenticate is called before any method; often you’ll have a situation where you only want to apply the before_filter to select methods. Check this out:

# apply authenticate to all methods
before_filter :authenticate
 
# apply authenticate to all methods EXCEPT index, and show
before_filter :authenticate, :except => [:index, :show]
 
# apply authenticate to ONLY the index and show
before_filter :authenticate, :only => [:index, :show]

So let’s review…in the previous section: we created a new landing page for our visitors, played with some if and for blocks, added basic HTTP authentication, and had a crash course on the before_filter. I’m sure you’ve been playing with the app in your browser, but if you haven’t…load up http://localhost:3000/books and you should be greeted with a familiar authentication dialog box!

Leave a comment, or send me an email with ideas for future articles! I wanted to cover SEO friendly URLs, validations, and a whole lot more this time but I wanted to get you guys an update sooner than later! Useful? Donate to my beer fund or digg this!

More Rails reading:

Understanding Rails partials

Rails Conference 2008

May 30th, 2008

No Gravatar

I’m down in Portland, OR this weekend for Rails Conf.

Officially, the conference spans four days, Thursday through Sunday. Since most of the sessions on the first day looked pretty basic, I skipped the first day. The Friday keynote was presented by Joel Spolsky. It was a light, good morning keynote about uber basics but I enjoyed it.

When the wi-fi doesn’t suck, I’ll set aside some time to keep you guys updated on the sessions that I’ve attended.

Rails Relationships

May 4th, 2008

No Gravatar

The Bookstore: A Rails 2.0 Tutorial…continued…who wants to play with relational databases? Here’s the section I’m sure you’ve all by dying for; sure, the scaffold was pretty bad ass, but now we’re going to play with something you ALL will enjoy. This segment is going to be a little bit longer than the others, we’ll be covering a lot of database information! Before you continue, I will assume that you have an understanding of the previous articles:

  1. Ruby on Rails Tutorial, now with more 2.0.2!
  2. Basic Rail’s routing and a journey into Views, and Controllers
  3. RESTful design and the HTTP request

If you’ve been tinkering with the old bookstore application, which I hope all of you have, there is a chance that it looks nothing how we left it. Do yourself and grab a fresh copy, which I will be using as the foundation for this segment.

With our last iteration of the bookstore we left with a simple, functional application that allowed us to build and maintain a database of books using the Rails’ scaffolding. Currently, our bookstore stores the title and description of a book; that’s not enough…I demand more! Don’t books have authors? Indeed they do. There are a few options, and it’s time for you to choose your own adventure…you want to add an author to your books, but there’s a fork in the road…which path do you take?

  1. Add a column to the existing Books database (create a database migration to add an “author” column to your existing database)
  2. Create a new Authors database (create a relational database)

Both are viable options, and it is likely you may not have any idea what the hell I am talking about. Let’s choose option two, by the time we work through this method, you will be able to use either method. Before we start coding, as with any project, it’s good to understand what we are trying to accomplish. Here’s the goal: create another database that contains authors, then relate this database with the existing book database.

Two Rails Databases

The first thing we’re going to do is create a separate database; which really, is just a table in the existing database. Using your friend the scaffold generator with one column for the authors “name”. Do you remember the syntax? Remember: models are singular…author, not authors!

ng:bookstore admin$ script/generate scaffold Author name:string
      exists  app/models/
      exists  app/controllers/
      exists  app/helpers/
      create  app/views/authors
      exists  app/views/layouts/
      exists  test/functional/
      exists  test/unit/
      create  app/views/authors/index.html.erb
      create  app/views/authors/show.html.erb
      create  app/views/authors/new.html.erb
      create  app/views/authors/edit.html.erb
      create  app/views/layouts/authors.html.erb
   identical  public/stylesheets/scaffold.css
  dependency  model
      exists    app/models/
      exists    test/unit/
      exists    test/fixtures/
      create    app/models/author.rb
      create    test/unit/author_test.rb
      create    test/fixtures/authors.yml
      exists    db/migrate
      create    db/migrate/002_create_authors.rb
      create  app/controllers/authors_controller.rb
      create  test/functional/authors_controller_test.rb
      create  app/helpers/authors_helper.rb
       route  map.resources :authors

Short and sweet. If you jumped the gun and tried to access: “http://localhost:3000/authors” you likely got an error. Did you run “rake db:migrate”? If so, do it now.

ng:bookstore admin$ rake db:migrate
(in /Users/admin/Desktop/bookstore)
== 2 CreateAuthors: migrating =================================================
-- create_table(:authors)
   -> 0.0040s
== 2 CreateAuthors: migrated (0.0043s) ========================================

Visit your new Authors section at “http://localhost:3000/authors” and add two authors. So, now we have a database of books and a database of authors, how do we tie these together? Allow me to introduce the “foreign key”, while this sounds super complex, I’ll simplify it for our purposes. Every record in our database has a unique ID, you may notice in our URLs we access our books and authors by “http://localhost:3000/books/1″ and “http://localhost:3000/authors/1″; these ID numbers correspond with our databases. Remember, these are unique! Take a look at the data from our the authors and books tables, take note that I ran out of room on my blog post to show the created_at and updated_at columns for the books table, trust me that it’s in the database.

By looking at the tables, you should be able to see how the relationship between the ID in authors table and the respective entry. To beat a dead horse, ID 1 from authors contains the following:

Barack Obama’s Record from Authors

  • ID = 1
  • name = Barack Obama
  • created_at = 2008-05-01 19:59:17
  • updated_at = 2008-05-01 19:59:17

Just as ID 2 from authors contains this set of data:

Bill Clinton’s Record from Authors

  • ID = 2
  • name = Bill Clinton
  • created_at = 2008-05-01 19:59:32
  • updated_at = 2008-05-01 19:59:32

Freakonomics Record from Books

If we look at the books table (keep in mind I didn’t show created_at or updated_at above), and look at the book with an ID of 1, we see:

  • ID = 1
  • title = freakonomics
  • description = Which is more dang…(truncated)
  • created_at = 2008-05-01 19:59:32
  • updated_at = 2008-05-01 19:59:32

If this looks repetitive and trivial, GREAT, that means it makes sense to you. I am showing three, simple examples because you MUST understand how these records are accessed. Still look foreign? Look over the examples a few more times, once it sinks in, we’ll take this a step further.

If you remember the task at hand, you’ll recall that we want to associate an author with a book. We’ll do this with a foreign key. What is that, well the reason I disassembled the database table structure for this reason exactly! Simply put, a foreign key is the ID of your record, in a table isn’t its own. If you place ID 1 from authors in the books table, you now have a foreign key. Not that cool….yet.

We don’t arbitrarily place the foreign key in the books table; foreign keys, by default are placed in their own column. Since we want to place the authors ID in the books table, we need a new column for this foreign key. It is convention to name these columns based on the origin of the foreign key; in this particular case, we would create a column named “author_id” to the table books. Okay…a little confusing still? Hang with me. I didn’t ask you to create any columns, so don’t worry…but let’s pretend we created author_id in books and the author_id column for our Freakonomics entry was assigned a value of “2″…it would looks like this:

  • ID = 1
  • title = freakonomics
  • description = Which is more dang…(truncated)
  • author_id = 2
  • created_at = 2008-05-01 19:59:32
  • updated_at = 2008-05-01 19:59:32

What does this author_id with a value of “2″ actually mean? Well, this foreign key tells us that if we look at the author table, and find record with an ID of “2″, all that data applies to our Freakonomics book! Currently, the only data in our authors table is a name, but what if it contained a lot more? Perhaps the author’s homepage, biography, age, etc!

By using a foreign key, we can keep data separate. This may not seem like a big deal right now, but imagine this scenario:

We have a million books all authored by the same guy, and instead of setting of a separate database for the book’s authors, we decided to put the author’s name, age, hair color, and publisher in out book table. Say the author changed their hair color, name, and found a new publisher. This sucks…not only are we repeating all this data in our books table, but we need to go through EACH record and change all of those fields.

Now image this…instead of just adding columns to our books table, we create a separate table called authors and in this table we add the columns: name, hair color, and publisher. In our books table, instead of having name, age, hair color, and publisher we have one foreign key column called author_id. Now that we use a foreign key to reference the secondary, related table we can easily update the required data fields!

Why did I take the time and teach you this? Even though Rails will handle most associations, you will require this basic understanding in order to create the foreign keys so Rails can perform its magic.

Rails Migrations

You may recall we run “rake db:migrate” after we generate a scaffold; we do this to create, or “migrate” or database to the most current version. You haven’t had to manually create any “migrations”, because Rails has automagically done it for you. Before we play with migrations, you should know what they are.

Back in the day, when developers worked on databases they would manually add tables (books, authors) and columns (name, description, title). No qualms here. The problem was, somewhere down the line if you wanted to remove a column, modify a table, change a field type, etc. You would again, manually modify the database. The end result is a database with the structure that you want, but let’s say you were trying to figure out the differences between your first and third version of your database. Not really possible…what migrations allow you to do is version control your database.

Here’s a bigger picture: As your development skills progress, you will likely move to a version control system for your code (git, subversion). Version control will allow you to save your code at different stages, and instantly revert to any of those saved stages (think saved game on the xbox). With version control in place, one version of your code might be looking for the title of your book; but down the road, you decided that the book title should really be called the this_is_the_book_title. You make the change to the database, renaming your title field to this_is_the_book_title. Let’s say you’ve done some more code, and realize that you made a mistake, and want to revert back to your saved version where the book title was actually called title.

Using your version control system, you quickly revert back to your saved version where your code references your Book.title (verses Book.this_is_the_book_title). The problem here is your database has a field called this_is_the_book_title. Of course, you can manually change this back; and with one or two fields this would be fine. Imagine if you changed hundreds of fields over hundreds of thousands of tables? Not so simple anymore!

Migrations, as you will see, allow for you make sure your code and your databases are in sync. Examples are golden, so open up /db/migrate/001_create_books.rb!

class CreateBooks < ActiveRecord::Migration
  def self.up
    create_table :books do |t|
      t.string :title
      t.text :description
 
      t.timestamps
    end
  end
 
  def self.down
    drop_table :books
  end
end

Off the bat, take note of the file name, “001_create_book.rb”. We know that this is the migration with number “001″ and the name “create_book”, we can see that this migration is the first, and it will create something called “book”. If you look in the db/migrate directory you will see the sequential list of files 002, 003, etc. Looking at the migration file I listed above, you’ll see a self.up and self.down. The code defined in self.up is what Rails runs when we migrate forward, the code in self.down is what is run when we migrate backwards.

When we run rake db:migrate, we ask Rails to bring our database up to the most current version, from 001 onwards; though we haven’t used it yet, we can just as easily bring the database back to the first day we created the application, we’d do this with:

rake db:migrate VERSION=1

Now, open up “/db/migrate/002_create_authors.rb” you should see this:

class CreateAuthors < ActiveRecord::Migration
  def self.up
    create_table :authors do |t|
      t.string :name

      t.timestamps
    end
  end

  def self.down
    drop_table :authors
  end
end

If we were to run the command “rake db:migrate VERSION=1” the first thing Rails would do, is figure out which version of the database it is currently at (Rails does this through a table called schema“. Once it finds the version, in this case, we are at version 2, it will proceed to run all the self.down code until it reaches the version we specified, in this case version 1. In this particular instance, Rails will first drop the table “authors”.

This may all be confusing to you, it was to me. As long as you understand the basic foundation, through repeated use, it will all make more sense. Alright, enough of that…time to play with Rails!

Rails Associations

Our original goal was to add author data to a particular book. Now that we’ve created a separate author database, let’s tie them together. You’re going to see why I spent so much time explaining foreign keys and migrations.

Under the hood, Rails is more than willing to simplify relational databases. The important thing about associations is to have a high level understanding of what belongs to what. Let me preface this by saying, I am aware this example can go multiple ways, so don’t nitpick ;) Anyways, with our Book example, let’s look at our books and authors. A book belongs to an author, and an author has many books? It just happens Rails has a has_many and belongs_to method. These are basic Rails associations, and we declare them in the model. Open up your model/book.rb and model/author.rb and add the following lines of code:

# in model/book.rb
class Book < ActiveRecord::Base
  belongs_to :author
end

# in model/author.rb
class Author < ActiveRecord::Base
  has_many :books
end

What we’ve done is set up the associations between the two models, now Rails knows to look for an additional piece of data, the foreign key, and will handle all the database queries for you! One thing of particular importance: you will notice that author is singular with belongs_to declaration, while the has_many is plural. I point this out because many of you will overlook this and wonder why your application is not working.

Adding a Foreign Key in Rails

Now that our associations are in place, let’s create a migration for adding the foreign_key. This migration will be called, “add author ID to books”, and to do this we’ll run this command:

script/generate migration add_author_id_to_books

ng:bookstore admin$ script/generate migration add_author_id_to_books
      exists  db/migrate
      create  db/migrate/003_add_author_id_to_books.rb

Open the file that was just generated. Remember everything I told you about foreign keys? We’re going to create a column called “author_id” in our Book table. Rails will see the relationship we declared in our model, and by using our foreign key, will be able to determine Author record matches up with our Book record.

class AddAuthorIdToBooks < ActiveRecord::Migration
  def self.up
    add_column :books, :author_id, :int
  end

  def self.down
    remove_column :books, :author_id
  end
end

Save the file, and run “rake db:migrate”. Another important tidbit: the rule of thumb is the foreign key should be created in the database whose model contains the “belongs_to” declaration, in this case, the Book table.

ng:bookstore admin$ rake db:migrate
(in /Users/admin/Desktop/bookstore)
== 3 AddAuthorIdToBooks: migrating ============================================
-- add_column(:books, :author_id, :int)
   -> 0.0200s
== 3 AddAuthorIdToBooks: migrated (0.0202s) ===================================

ng:bookstore admin$

Modifying the View

Before you get took excited, there are a few things we need to do. Our backend is complete, now we need to modify some views so we can pair the page our users see to our backend database. Let’s start by adding few lines of code to the Books view. Open: app/views/books/new.html.erb:

<h1>New book</h1>
 
<%= error_messages_for :book %>
 
<% form_for(@book) do |f| %>
 
 
    <b>Title</b>
    <%= f.text_field :title %>
 
 
 
    <b>Description</b>
    <%= f.text_area :description %>
 
 
 
    <b>Author:</b>
    <%= collection_select(:book, :author_id,  Author.find(:all, :order => "name") , :id, :name) %>
 
 
 
    <%= f.submit "Create" %>
 
 
<% end %>
 
<%= link_to 'Back', books_path %>

We just modified the view when the “new” method is called in our Books controller. We called on method from the Rails FormHelper library, here’s quick breakdown of what the collection select does:

<%= collection_select(:book, :author_id,  Author.find(:all, :order => "name") , :id, :name) %>
 
# This returns the following HTML 
<select id="book_author_id" name="book[author_id]">
	<option value="THE AUTHOR ID">THE AUTHOR TITLE</option>
</select>

Accessing Associated Data Fields

Up to this point, I feel like I’ve been doing everything for you ;) I’m going to give you a small piece of information, then ask you to complete a task. When we set up the associations we specified the following:

  1. An author has_many :books
  2. A book belongs_to :author

Visualizing and setting up associations is really the most difficult part, Rails really takes on the rest of relational tasks. Recall, the author table contains the name field, since we told Rails that an author has many books, and a book belongs to an author; we can access the associated field using the following:

# returns the book title
<%= @book.title %>
 
# returns the authors name
<%= @author.name %>
 
# returns the associated author's name
<%= @book.author.name %>

Now spend a few minutes, and alter the rest of the views in app/views/books; leave the index view alone for now. If you get stuck, this is what they should look like:

# app/views/books/edit.html.erb
<h1>Editing book</h1>
 
<%= error_messages_for :book %>
 
<% form_for(@book) do |f| %>
 
 
    <b>Title</b>
    <%= f.text_field :title %>
 
 
 
    <b>Description</b>
    <%= f.text_area :description %>
 
 
 
    <b>Author:</b>
    <%= collection_select(:book, :author_id,  Author.find(:all, :order => "name") , :id, :name) %>
 
 
 
    <%= f.submit "Update" %>
 
 
<% end %>
 
<%= link_to 'Show', @book %> |
<%= link_to 'Back', books_path %>
# app/views/books/show.html.erb
 
 
  <b>Title:</b>
  <%=h @book.title %>
 
 
 
  <b>Description:</b>
  <%=h @book.description %>
 
 
 
  <b>Author:</b>
  <%=h @book.author.name %>
 
 
<%= link_to 'Edit', edit_book_path(@book) %> |
<%= link_to 'Back', books_path %>

Alright! Since we added a foreign key column, our old data will not have a value for its foreign key. We could simply delete the old record or modify it so it is up to date, but I want to introduce a handy little feature: resetting the database! With the “rake db:reset” command, Rails drops and recreates the current database from db/schema.rb for the current environment. Run it!

ng:bookstore admin$ rake db:reset
(in /Users/admin/Desktop/bookstore)
"db/development.sqlite3 already exists"
-- create_table("authors", {:force=>true})
   -> 0.0043s
-- create_table("books", {:force=>true})
   -> 0.0042s
-- initialize_schema_information()
   -> 0.0439s
-- columns("schema_info")
   -> 0.0007s
ng:bookstore admin$

All Systems Go

FIRE UP YOUR SERVER! Proceed to add a few authors via /authors…

…then add a few books via /books; notice the drop down menu? Success!

Finally, click on a book and get a more detailed picture…see the associated author? Ahhh! The fruits of your labor!

Under The Hood

If you’re curious what is happening when you’re creating or viewing records, take a look at your console. Behold, the power of Rails!

Accessing /books/new:

Processing BooksController#new (for 127.0.0.1 at 2008-05-04 23:26:02) [GET]
  Session ID: BAh7ByIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6Rmxhc2g6OkZsYXNo%0ASGFzaHsABjoKQHVzZWR7ADoMY3NyZl9pZCIlZGEyMjY4MzgzZDQ1MGU4NjE1%0ANDEwMDlmY2VlYjJhZGI%3D--fb8c96ae999682b51105e633e7e6da0c3d008cf1
  Parameters: {"action"=>"new", "controller"=>"books"}
Rendering template within layouts/books
Rendering books/new
  Author Load (0.000754)   SELECT * FROM authors ORDER BY name
Completed in 0.01405 (71 reqs/sec) | Rendering: 0.00755 (53%) | DB: 0.00075 (5%) | 200 OK [http://localhost/books/new]

On the creation of a book:

Processing BooksController#create (for 127.0.0.1 at 2008-05-04 23:26:48) [POST]
  Session ID: BAh7ByIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6Rmxhc2g6OkZsYXNo%0ASGFzaHsABjoKQHVzZWR7ADoMY3NyZl9pZCIlZGEyMjY4MzgzZDQ1MGU4NjE1%0ANDEwMDlmY2VlYjJhZGI%3D--fb8c96ae999682b51105e633e7e6da0c3d008cf1
  Parameters: {"commit"=>"Create", "authenticity_token"=>"82b54355dede97ccb50e1bfa90ab3c5ffcf081ae", "action"=>"create", "controller"=>"books", "book"=>{"title"=>"Don't Make Me Think", "description"=>"Usability design is one of the most important--yet often least attractive--tasks for a Web developer. In Don't Make Me Think, author Steve Krug lightens up the subject with good humor and excellent, to-the-point examples.", "author_id"=>"2"}}
  Book Create (0.000378)   INSERT INTO books ("updated_at", "title", "description", "author_id", "created_at") VALUES('2008-05-04 23:26:48', 'Don''t Make Me Think', 'Usability design is one of the most important--yet often least attractive--tasks for a Web developer. In Don''t Make Me Think, author Steve Krug lightens up the subject with good humor and excellent, to-the-point examples.', 2, '2008-05-04 23:26:48')
Redirected to http://localhost:3000/books/3
Completed in 0.01351 (74 reqs/sec) | DB: 0.00038 (2%) | 302 Found [http://localhost/books]

Viewing a single book’s details:

Processing BooksController#show (for 127.0.0.1 at 2008-05-04 23:27:37) [GET]
  Session ID: BAh7ByIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6Rmxhc2g6OkZsYXNo%0ASGFzaHsABjoKQHVzZWR7ADoMY3NyZl9pZCIlZGEyMjY4MzgzZDQ1MGU4NjE1%0ANDEwMDlmY2VlYjJhZGI%3D--fb8c96ae999682b51105e633e7e6da0c3d008cf1
  Parameters: {"action"=>"show", "id"=>"2", "controller"=>"books"}
  Book Load (0.000247)   SELECT * FROM books WHERE (books."id" = 2)
Rendering template within layouts/books
Rendering books/show
  Author Load (0.000246)   SELECT * FROM authors WHERE (authors."id" = 3)
Completed in 0.01162 (86 reqs/sec) | Rendering: 0.00550 (47%) | DB: 0.00049 (4%) | 200 OK [http://localhost/books/2]

Until next time

Four tutorials in, you guys should know the drill by now :) Next time I’ll be covering validations, routing, and maybe even some Rails SEO. Useful? Donate to my beer fund!

The next post has been posted! It covers partials, the before filter, and basic HTTP authentication.

For further reading, take a look at the Rails API, it is an invaluable reference:
Module: ActiveRecord::Associations::ClassMethods

No Gravatar

One of the biggest changes in Rails 2.0 is the way the framework pimps RESTful design.

??!@#$%^&*??

My thoughts exactly. Understanding what REST was/did/accomplsiehd was a bit of a struggle for me, hopefully, I can do a good job of breaking the concept down into tasty, digestible portions.

Disclaimer:
If you’re a robotic code monkey like myself, my over-simplified terminology may anger you. By all means, if I am incorrect, which I often am…correct me…but please…think of the kids! Don’t nitpick, it’s just not cool.

The HTTP Request

Before I can explain what REST is, you need to have a basic understand of how your web browser communicates with web servers. Let’s start with something you are familiar with. When you visited my blog, this is what happened:

  1. You typed in www.jonathansng.com

  2. Your browser sent a request to the server

  3. My server responded with HTML

  4. Your browser rendered that HTML

Well…beneath all this seemingly simple transaction, a few more, albeit important things are occurring. Using the same example as above, this is what is really happening:

  1. You typed in www.jonathansng.com

  2. Your browser sent a request to the server (called an HTTP request)

  3. My server responded to that HTTP request

  4. Your browser rendered the HTML that was returned

A HTTP request is like a little sticky note that is passed on to the web server. When the web server gets this note, it can read over the note and determine what action it needs to take place. There are eight different kinds of HTTP requests.

There are two kinds of requests that you should be most comfortable with. The “GET” request and the “POST” request. The “GET” request does exactly what it states, it gets the content of some resource from the server, identified by the URL Working with HTML, it should come as no surprise that the “POST” request is used to send (or POST) data to a URL, eventually creating a new resource.

Resources

I hate to use technical jargon, but some things can’t be side-stepped. Okay, take a deep breath and clear your mind. Stop thinking of the internet as “web pages”, from now on when you’re in Rails land, you need to think of the internet as a “resource.”

You might be a little bit confused, because as I’m writing this, I’m trying to think of a good example. Okay.

Let’s say you click through my site…the about résumé, my portfolio, and about me page. Web pages right? Wrong. These are resources! Take my résumé for example; if I printed it out on paper and handed it to you, it’d still contain everything you’d see if you would have accessed it on the web…but now it’s on paper! What if I took a screen capture and saved it as a JPG; or how about an Adobe PDF? Do you see where I’m going with this?

The “web page” you accessed was just one way to format the resource, in this case, my résumé.

The OTHER HTTP requests

Stick with me for a little while longer. Earlier, I mentioned there were eight types of HTTP requests, well here are all of the HTTP requests:

  1. HEAD
  2. GET
  3. POST
  4. PUT
  5. DELETE
  6. TRACE
  7. OPTIONS
  8. CONNECT

All I want is for you to be aware of these request types, I’m sure you already guess what a few of these do, but don’t freak out if you have no idea.

Let’s tie it all together

Let’s use our Bookstore application as an example. Now, what if I were to tell you this URL could do two different things:

  • http://localhost:3000/books/1

Say what? Do you remember what I said about HTTP requests?

Okay…imagine this…say you want to view book #1, when you click the above URL you are sending a HTTP “GET” request to the server; once the server gets your HTTP request it responds with the information you requested, in this case the title and description for book #1.

Well, after reading over the description I’ve decided book #1 sucks. I want to delete it. If you mouse over the “Destroy” URL for the bookstore app, you’ll notice the URL is as follows:

  • http://localhost:3000/books/1

Hey wait…that’s the same URL as the “Show” link! You are 100% correct. So how can one URL serve multiple purposes? You guessed it, the HTTP request!

When you click the “Destroy” link, you’re sending a HTTP “DELETE” request to the web server. When the web server gets your request it sees you want to DELETE book #1.

Crazy.

Take some time to let this all soak in, it’s actually quite important. You’ll see just how important this RESTful design is when we start digging into our Bookstore application.

You may have noticed I haven’t explained what REST actually stands for, honestly, I have no idea, does it really matter….probably not, but if you’re particularly curious, Wikipedia has the no-nonsense low down on everything we’ve discussed and then some.

I think this is a good point to take a break, not to mention it’s 11PM and I want to play Call of Duty 4. Recently, I added my blog to feedburner, if you want an instant update when I add a new post, subscribe! As usual, leave me a comment for better or worse…if you’re feeling like a badass you can even Digg this or donate to my beer fund!

Until next time folks….

The next tutorial has been published: Rails’ Relationships

No Gravatar

Basic Rail’s routing and a journey into the controller

Thanks for tuning in! Last time we spoke, we set up a basic Rails application called the bookstore. Using the new 2.0 scaffolding, we were able to quickly, and effortlessly move from a high-level thought process to a living, breathing model. Now that you’ve toyed around with the application source, I’m going to explain our previous code and I’ll even throw a little wrench into your gears…basic Rail’s routing.

Open up your bookstore application, if you’ve lost it or found this post randomly…be sure to visit the original post “Ruby on Rails Tutorial, now with more 2.0.2!“. Then, fire up your server, and navigate to your application’s root, likely, http:/localhost:3000. If your code is untouched from the last time we met, you should encounter a “routing error” like so:

02_routing.jpg

That’s kind of annoying, and just a little bit ugy; it’s time we fix this! You may remember play with .htaccess and doing a mod_rewrite here and there, when you use the Rails framework you no longer place the burden of URL rewriting on the webserver, but instead, on Rails. Routes can get really complicated, really fast; so I am going to show you the very basics. Even after I show you how to play around with Rails’ routing, I will leave the application’s default routes alone. I will do this because in teaching, it is much easier explaining to you that:

http://localhost:3000/books/1

is calling on the “books” controller, with the “show” method, and an “id” of 1 verues trying to explain to you that,

http://localhost:3000/library/freakonomics

can do the exact same thing! All in time though, all in time. Anyways, open up theconfig/routes.rb file and you should see something like this:

Routes are listed in order of priority, the higher on the list they are, the higher priority they are. You’ll notice Rails’ default routes on the bottom:

 map.connect ':controller/:action/:id'
 map.connect ':controller/:action/:id.:format'

Briefly, when a visitor types in the URL:

http://localhost:3000/books/1

Rails takes the HTTP request, looks through the routes listing, and systematically tries to find a match. With the URL above, the HTTP request will be matched to the first request and processed as follows:

http://localhost:3000/:controller/:action/:id

Hopefully this makes sense, I’ll touch more on this down the road. If you’re not entirely lost, recall that the reason we’re poking around the routes file is because we are getting a routing error when we attempt to access “http://localhost:3000″. At the end of the routes.rb file, add the following:

map.root :controller => "books", :action => "index"

“map.root” is the shorthand to name the root path “”; now whenever we navigate to the site’s root path we should see a call to the “books” controller and “index” action. Take note, you do not have to specificy the “index” action, as it is called by default, but I included it for sake of illustration. Navigate to your site’s root, and watch the magic.

Pretty neat, huh? Add a few more books, and then take some time to examine the URL structure of the database items you’ve entered. When you’ve done that, open up the “apps/models/book.rb” file. The file you just opened is our “Book model”, it acts as the gateway between any database queries. Right now it is empty, but it is worth pointing out. Now open the, “apps/controllers/books_controller.rb” file, you will see first entry is the index method.

  # GET /books
  # GET /books.xml
  def index
    @books = Book.find(:all)
 
    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @books }
    end
  end

Since this code was generated by Rails, we have a few lines of commenting. What this means is, any GET request to /books will actaully call the “index” method (we’ll talk about the different request types later). When this method is called in, there are two things that happen.

  1. We are talking to our “Book model” and asking it to find all records, then we are saving those results as a Ruby hash in “@books”
  2. Next, depending on the requested format, responding with either an HTML template or XML template (more on this later)

For those readers who have some database expereince, check this out, if this doesn’t make sense, don’t worry.

    # ask the Book model to find :all records
    @books = Book.find(:all)
 
    # the resulting MySQL query
    SELECT * FROM books

Now, scroll down to the next method…it should be named “show”.

  # GET /books/1
  # GET /books/1.xml
  def show
    @book = Book.find(params[:id])
 
    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @book }
    end
  end

This time, instead asking the Book model to find :all records, we’re asking it to find by the “params[:id]“. What does “params[:id]” mean? The “id” parameter from the URL is accessed by “params[:id]” and in this case, the value is “1″. If we were to type the URL, “http://localhost:3000/books/5″, params[:id] would be set to “5″. Let’s look at this line of code:

@book = Book.find(params[:id])

What we’re doing is assigning the results of our database query, in this case, by asking the Book model to find the record with ID matching params[:id]. You’ll notice that all models are titleized and singular: in this case Book, but it could easily be Author or Category.

Now that you’ve seen how we are retrieving our data from the database, let me show you how to format that data for your visitors. Open your “app/views/books/index.html.erb” file. And you should see this:

If you’ve developed websites in the past, the show view should be a little more familar to you. You will notice a few things that look out of place, with PHP we enclosed our code with the <? code ?> tags, with Ruby, anything enclosed between <% code %> , <%= code %>, is called embedded ruby. Here are the differences:

  • <% code %> is evaluted, but not printed
  • <%= code %> is evaulated, and printed

Check this:

1
2
3
4
5
# this will display NOTHING in your HTML
<% "You will not see this" %>
 
# this will print the string
<%= "But you will see this!" %>

You can test the code by pasting the embedded ruby code, just below the “<h1>Listing Books</h1>” tag, and accessing your site’s root, like so:

See how that works? Now, the final piece of the puzzle!

<% for book in @books %>
<tr>
<td><%=h book.title %></td>
<td><%=h book.description %></td>
<td><%= link_to 'Show', book %></td>
<td><%= link_to 'Edit', edit_book_path(book) %></td>
<td><%= link_to 'Destroy', book, :confirm => 'Are you sure?', :method => :delete %></td>
</tr>
 
<% end %>

What we’re doing here, is looping through each item in the @books hash, and for each item we are printing out the book title, “book.title” and book description, “book.description”. The “h” you see preceeding the book title and description is the Rails “HTML escape”. If you type <%= book.title %> instead of <%=h book.title %>, the book title will still dispaly, BUT it is good habit to ALWAYS HTML escape database fields with data that may contain something harmful…read: malicious users entering something other than a book description.

Take a look at the code again, if I were to read it out loud to you it would read as follows:

“For each book in the @books variable, do the following: Print the title; description; and the show, edit, and destroy commands”. To expand on the whole “for” block, here’s another example…if you were feeling rather rebelious, you could do this too:

1
2
3
4
5
6
7
8
9
10
<% for item in @books %>
<tr>
<td><%=h item.title %></td>
<td><%=h item.description %></td>
<td><%= link_to 'Show', item %></td>
<td><%= link_to 'Edit', edit_book_path(item) %></td>
<td><%= link_to 'Destroy', item, :confirm => 'Are you sure?', :method => :delete %></td>
</tr>
 
<% end %>

Hopefully that makes some more sense :) As always, if this was this helpful, if you have questions, or if you just want to bullshit…leave me a comment…help me, help you! Feel like donating to my beer fund?

The next part of our journey through Rails covers RESTful design, an integral part of a properly designed and correctly executed Rails web application.

PHP vs Rails

April 4th, 2008

No Gravatar

I was milling over some old PHP code today, funny, because my friend Norm linked me to David Hansson’s blog post…it looks like PHP is a Friday thing!

After looking at my old code, I thought to myself, hmm, what better time to showcase the beauty of Rails. I made a post on a message board I frequent, and there was quite a bit of discussion. Anyways, take a look at this!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
header("Content-type: text/html; charset=utf-8");
include_once('inc.functions.php');
require('inc.drawrating.php');
 
$uid = $_GET['uid'];
 
$conn= mysql_connect("localhost","db","dbpassword") or die (mysql_error());
mysql_select_db(ave_development) or die(mysql_error());
 
 
$q = "SELECT views FROM stores WHERE uid=$uid";
$result = mysql_query($q,$conn);
$tmp = mysql_fetch_object($result);
$views = $tmp->views;
$views++;
 
$lview = date("Y-m-d H:i:s");
$q = "UPDATE stores SET views=$views, last_view='$lview' WHERE uid=$uid";
mysql_query($q, $conn);
 
$q = "select * from stores where uid = $uid";
$result = mysql_query($q,$conn