--0016367faf8b6130c50499495909
Content-Type: text/plain; charset=ISO-8859-1

Good Afternoon,

On Thu, Jan 6, 2011 at 10:11 AM, SW Engineer <abder.rahman.ali / gmail.com>wrote:

> Following the "Ruby on Rails Tutorial", and under section "6.1.1
> Database migrations"
> http://railstutorial.org/chapters/modeling-and-viewing-users-one#top
>
> There is the following migration:
>
> class CreateUsers < ActiveRecord::Migration
>  def self.up
>    create_table :users do |t|
>      t.string :name
>      t.string :email
> .
> .
>

This is rather easy to explain actually. What occurs is this - you are
calling the create_table method. This method is getting two parameters - the
:users symbol which is used to define the table name and then the "do"
block. The block acts as a sort of internal proc to the create_table method.
The magic happens when the create_table method "yields" back to the block.
In this case the yield call from the create_table method is passing in a
parameter which is referenced as "t" by the block. Then what occurs is that
the block is executed as a procedure using the object passed into it by the
create_table method as the "t" variable. It simply is a helper concept to
ease the creation of your table. So you can sort of view it as "create a
table named users and then with that table do the following - add a string
column called name and a string column called email"

As you can note here
http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-create_table-
there is no requirement to use the block form at all - it's simply a
convenience and aesthetic method for the most part. It's also good to hit
the view source "button" at the bottom of the method definition. You'll
notice that there is a

yield table_definition if block_given?

line. This line is where the table_definition variable that is created
within the create_table method is passed back to the block which has been
setup to refer to it as "t". That table_definition variable is then modified
via the string method calls on it. Then at the end of the block the
create_table method continues and thus you get your create table statement
fully populated and then executed.

Hope this helps

John

--0016367faf8b6130c50499495909--