This tutorial is taken from the book “Ruby on Rails Made Easy by Justin Williams”. It’s a very good beginners guide but some of the code are not compatible with the new version of RoR. I repost it here with the necessary changes. I have remove a lot of the explanations and simplify the whole tutorial. If you like to understand more about the code syntax visit http://www.rubyonrails.org/docs or consider buying the book.

I am making use of a all-in-one development environment called Instant Rails. Instant Rails is a one-stop Rails runtime solution containing Ruby, Rails, Apache, and MySQL, all preconfigured and ready to run. No installer, you simply drop it into the directory of your choice and run it. It does not modify your system environment.

Installation

Download and install “Instant Rails” from http://instantrails.rubyforge.org/wiki/wiki.pl

Creating a Rails project

Open up a new command prompt window (Start ➤ Run ➤ cmd) and navigate to the directory where instant rails is located.

Type use_ruby at the command prompt and press Enter. These setup the environment you need to create a new application.

To create a new project with the name railslist, type rails railslist at the command prompt and press Enter. Your output look similar to this.

G:\InstantRails-2.0-win\rails_apps>rails railslist

create

create app/controllers

create app/helpers

create app/models

create app/views/layouts

create config/environments

create config/initializers

create db

create doc

create lib

create lib/tasks

create log

create public/images

create public/javascripts

create public/stylesheets

create script/performance

create script/process

create test/fixtures

create test/functional

create test/integration

create test/mocks/development

create test/mocks/test

create test/unit

create vendor

create vendor/plugins

create tmp/sessions

create tmp/sockets

create tmp/cache

create tmp/pids

create Rakefile

create README

create app/controllers/application.rb

create app/helpers/application_helper.rb

create test/test_helper.rb

create config/database.yml

create config/routes.rb

create public/.htaccess

create config/initializers/inflections.rb

create config/initializers/mime_types.rb

create config/boot.rb

create config/environment.rb

create config/environments/production.rb

create config/environments/development.rb

create config/environments/test.rb

create script/about

create script/console

create script/destroy

create script/generate

create script/performance/benchmarker

create script/performance/profiler

create script/performance/request

create script/process/reaper

create script/process/spawner

create script/process/inspector

create script/runner

create script/server

create script/plugin

create public/dispatch.rb

create public/dispatch.cgi

create public/dispatch.fcgi

create public/404.html

create public/422.html

create public/500.html

create public/index.html

create public/favicon.ico

create public/robots.txt

create public/images/rails.png

create public/javascripts/prototype.js

create public/javascripts/effects.js

create public/javascripts/dragdrop.js

create public/javascripts/controls.js

create public/javascripts/application.js

create doc/README_FOR_APP

create log/server.log

create log/production.log

create log/development.log

create log/test.log

To see your new website.

Start Instant Rails by executing InstantRails.exe. By default, both Apache and Mysql should be started.

Click on the I icon select “Rails Application>Manage application”, you see a list of application including railslist.

To start the web server check railslist and click the button “Start with Mongrel”. A command prompt window will show you the URL where the new site is located such as http://localhost:3000. Type this in your web browser and you should see this page.

Creating the database

We use phpmyadmin to create 3 new database. Go to your browser and type in http://loclhost/mysql/

you enter the phpmyadmin page.

Enter railslist_development in the “Create new Database” text box and click the button “Create”.

Repeat and create railslist_test and railslist_deployment databases.

Telling Rails about the databases

Open InstantRails-2.0-win\rails_apps\railslist\config\database.yml with your text editor and make the following changes

development:
adapter: mysql
database: railslist_development
username: root
password:
host: localhost
timeout: 5000

# Warning: The database defined as ‘test’ will be erased and
# re-generated from your development database when you run ‘rake’.
# Do not set this db to the same as development or production.
test:
adapter: mysql
database: railslist_test
username: root
password:
host: localhost

production:
adapter: mysql
database: railslist_deployment
username: root
password:
host: localhost

Creating the model

To use the model generator for this example, open up a command prompt, go to the directory in which the application is located, and then type ruby script/generate model Classified. You should see the following:

cd ~/railslist/

ruby script/generate model Classified

exists app/models/

exists test/unit/

exists test/fixtures/

create app/models/classified.rb

create test/unit/classified_test.rb

create test/fixtures/classifieds.yml

create db/migrate

create db/migrate/001_create_classifieds.rb

You’re telling the generator to create a model called Classified to store instances of classified ads. Each time you create a Classified model, you’re pulling a row from the database table.

Rails migrations

A migration file contains basic Ruby syntax that describes the data structure of a database table. It is used to create the tables in your database.

Go to your railslist directory and open up the 001_create_classifieds.rb file in the InstantRails-2.0-in/rails_apps/railslist/db/migrate folder. Replace the default code in your 001_create_classifieds.rb migration file with the following and save your changes:

class CreateClassifieds < ActiveRecord::Migration

def self.up

create_table :classifieds do |t|

t.column :title, :string

t.column :price, :float

t.column :location, :string

t.column :description, :text

t.column :email, :string

t.column :created_at, :timestamp

t.column :updated_at, :timestamp

end

end

def self.down

drop_table :classifieds

end

end

Migrations support all the basic data types: :string, :text, :integer, :float, :datetime, :timestamp, :time, :date, :binary and :boolean:

:string is for small data types such as a classified title

:text is for longer pieces of textual data, such as the description

:integer is for whole numbers

:float is for decimals

:datetime and :timestamp store the date and time into a column

:date and :time store either the date only or time only

:binary is for storing data such as images, audio, or movies

:boolean is for storing true or false values

Go to a command prompt and go to the InstantRails-2.0-in/rails_apps/railslist/ directory, in which

the application is located, and then type rake db:migrate

rake db:migrate

(in G:/InstantRails-2.0-win/rails_apps/railslist)

== 1 CreateClassifieds: migrating =============================================

– create_table(:classifieds)

-> 2.6970s

== 1 CreateClassifieds: migrated (2.6970s) ====================================

The database now has a table in which to store the classified ad data

Creating the controller

Now you need to write the basic code to manipulate the model. To create a controller, open up a command prompt and go to the directory in which the application is located; then type ruby script/generate controller Classified

ruby script/generate controller Classified

exists app/controllers/

exists app/helpers/

create app/views/classified

exists test/functional/

create app/controllers/classified_controller.rb

create test/functional/classified_controller_test.rb

create app/helpers/classified_helper.rb

Open classified_controller.rb file located under app/controllers. Modify the file to look like the following and save your changes:

class ClassifiedController < ApplicationController
def list
@classifieds = Classified.find(:all)
end
def show
@classified = Classified.find(params[:id])
end
def new
end
def create
end
def edit
end
def update
end
def delete
end
end

Creating the views

Create a file called list.rhtml using your favorite text editor and save it to InstantRails-2.0-in/rails_apps/railslist/app/views/classified. After creating and saving the file, refresh your web browser. You should see a blank page; if you don’t, check the spelling of your file and make sure that it is the exactly the same as your controller’s method.

Put some code into the list.rhtml file.

<% if @classifieds.blank? %>

<p>There are not any ads currently in the system.</p>

<% else %>

<p>These are the current classified ads in our system</p>

<ul id=”classifieds”>

<% @classifieds.each do |c| %>

<li><%= link_to c.title, {:action => ’show’, :id => c.id} -%></li>

<% end %>

</ul>

<% end %>

<p><%= link_to “Add new ad”, {:action => ‘new’ }%></p>

Creating the first objects

Go back to your classified_controller.rb file in InstantRails-2.0-in/rails_apps/railslist/app/controllers and edit the new method to look like this:

def new

@classified = Classified.new

end

The line you added to the new method lets Rails know that you will create a new object in this view. Create the corresponding new.rhtml file in InstantRails-2.0-in/rails_apps/railslist/app/views/ classified.

You’ll create a basic input form to accept new classified postings. Add the following code to the new.rhtml file and save it:

<h1>Post new classified</h1>

<% form_tag ‘create’ do -%>
<p><label for=”classified_title”>Title</label><br/>
<%= text_field ‘classified’, ‘title’ %></p>
<p><label for=”classified_price”>Price</label><br/>
<%= text_field ‘classified’, ‘price’ %></p>
<p><label for=”classified_location”>Location</label><br/>
<%= text_field ‘classified’, ‘location’ %></p>
<p><label for=”classified_description”>Description</label><br/>
<%= text_area ‘classified’, ‘description’ %></p>
<p><label for=”classified_email”>Email</label><br/>
<%= text_field ‘classified’, ‘email’ %></p>

<%= submit_tag ‘Create’ %>
<% end -%>
<%= link_to ‘Back’, {:action => ‘list’} %>

Edit the create method in the classified_controller.rb to match the following:

def create

@classified = Classified.new(params[:classified])

if @classified.save

redirect_to :action => ‘list’

else

render :action => ‘new’

end

end

Go to your browser and visit http://localhost:3000/classified/new, enter some data into the form, and submit it.

The data should submit successfully and redirect you to the list page, in which you now have a single item listed. If you click the link, you should see another Template is missing error since you haven’t created the template file yet.

Create a show.rhtml file under InstantRails-2.0-in/rails_apps/railslist/app/views/classified and populate it with the

following code:

<h1><%= @classified.title %></h1>

<p><strong>Price: </strong> $<%= @classified.price %><br />

<strong>Location: </strong> <%= @classified.location %><br />

<strong>Date Posted:</strong> <%= @classified.created_at %><br />

<strong>Last updated:</strong> <%= @classified.updated_at %>

</p>

<p><%= @classified.description %></p>

<hr />

<p>Interested? Contact <%= mail_to @classified.email -%></p>

<%= link_to ‘Back’, {:action => ‘list’} %>

Updating existing ads

Modify the classified_controller.rb edit and update methods to look like the following:

def edit

@classified = Classified.find(params[:id])

end

def update

@classified = Classified.find(params[:id])

if @classified.update_attributes(params[:classified])

redirect_to :action => ’show’, :id => @classified

else

render :action => ‘edit’

end

end

Create a new file called edit.rhtml and save it in InstantRails-2.0-in/rails_apps/railslist/app/views/classified. Populate

it with the following code:

<h1>Editing Classified: <%= @classified.title -%></h1>

<% form_tag( {:action => ‘update’, :id => @classified}) do %>

<p><label for=”classified_title”>Title</label><br/>

<%= text_field ‘classified’, ‘title’ %></p>

<p><label for=”classified_price”>Price</label><br/>

<%= text_field ‘classified’, ‘price’ %></p>

<p><label for=”classified_location”>Location</label><br/>

<%= text_field ‘classified’, ‘location’ %></p>

<p><label for=”classified_description”>Description</label><br/>

<%= text_area ‘classified’, ‘description’ %></p>

<p><label for=”classified_email”>Email</label><br/>

<%= text_field ‘classified’, ‘email’ %></p>

<%= submit_tag “Save changes” %>

<% end -%>

<%= link_to ‘Back’, {:action => ‘list’ } %>

edit the list.rhtml file go to the <li></li> element and modify it to look like the following:

<li>

<%= link_to c.title, {:action => “show”, :id => c.id} -%>

<small> <%= link_to ‘Edit’, {:action => “edit”,

:id => c.id} %></small>

</li>

Point your browser to http://localhost:3000/classified/list and test the new functionality.

Removing an ad

modify list.rhtml

Go to the <li></li> element and modify it to look like the following:

<li>

<%= link_to c.title, {:action => ’show’, :id => c.id} -%>

<small> <%= link_to ‘Edit’, {:action => ‘edit’,

:id => c.id} %></small>

<small> <%= link_to “Delete”, {:action => ‘delete’, :id => c.id},

:confirm => “Are you sure you want to delete this item?” %></small>

</li>

Open classified_controller.rb and modify the delete method as follows:

def delete

Classified.find(params[:id]).destroy

redirect_to :action => ‘list’

end

Adding some style

Add a new file called standard.rhtml to InstantRails-2.0-in/rails_apps/railslist/app/views/layouts.

Open up the classified_controller.rb file in app/controllers and add the following line just below the first line:

layout ’standard’

You are telling the controller that you want to use the layout in the standard.rhtml file.

go to http://localhost:3000/classified/list you should see that the template is now implemented,

Create a new file called style.css and save it in InstantRails-2.0-in/rails_apps/railslist//public/stylesheets.

* {

margin: 0;

padding:0;

}

body {

font-family: Helvetica, Geneva, Arial, sans-serif;

font-size: small;

font-color: #000;

background-color: #fff;

}

a:link, a:active, a:visited {

color: #CD0000;

}

a:hover {

color: #F70000;

}

input { margin-bottom: 5px;}

p { line-height: 150%; }

div#container {

width: 760px;

margin: 0 auto;

}

div#header {

text-align: center;

padding-bottom: 15px;

}

div#content {

float: left;

width: 450px;

padding: 10px;

}

div#content h3 {

margin-top: 15px;

}

ul#classifieds {

list-style-type: none;

}

ul#classifieds li {

line-height: 140%;

}

div#sidebar {

width: 200px;

margin-left: 480px;

}

Refresh your browser and you should see your application displayed with a bit more style. Thats all folks!

Leave a Reply