
Creating a Ruby Weblog in 10 Minutes
Contributed by Brian Leonard, maintained by Chris Kutler
June 2009 [Revision number: V6.7-1]
In this tutorial, you use the Ruby support in the NetBeans IDE to create and
run a simple database web application.
By completing
the steps in this tutorial, you learn how
to do the following tasks:
- Use Rake tasks and migration files
to create and update database tables
- Use the scaffold generator to generate
a basic create, read, update, delete (CRUD)
database web application
- Edit views to
fine-tune the web pages
If you are new to the NetBeans IDE, you might want to complete
the NetBeans IDE Ruby Quick Start Tutorial before
you follow this tutorial so that you are more familiar with
the UI.
Contents
To complete this tutorial, you need the following software and resources.
Creating the Ruby on Rails Project
You begin by creating a Ruby on Rails project.
By default, the IDE creates the project
in a directory structure that conforms to
the Ruby on Rails project conventions for applications.
In the NetBeans IDE, choose File >
New Project.
Select Ruby from the Categories list and
Ruby on Rails Application from
the Projects list, as shown in the following figure.

- Click Next to name the project and specify its location.
-
Type rubyweblog in the Project Name text
box,
as shown in the following figure.
Accept all the other default settings on this page.
You must choose the built-in version of JRuby.

Skip to Step 8 if the following conditions apply:
- You are using the default
root user name.
root access does not require a password.
- You are using the MySQL database server.
The IDE assumes these conditions by default.
-
Click Next to configure the database access.
Select the Specify Database Information
Directly option,
select the Database Adapter, and type the User Name and
Password. Leave
the Database Name set to rubyweblog_development.
- Click through to the Install Rails page. This page allows you to update Rails, install JRuby Open SSL support, install Warbler, and install or update the GlassFish Gem server. It also lets you change proxy settings.

Click Finish to create the new project.
The IDE creates the project directory with the same name as your
project
and opens the database.yml file in the editing area.
Verify that the development section's adapter, database,
user name, and password settings are
correct for the development and test configurations,
then click the small x button in the database.yml
tab to close
the file.

Creating the Scaffold
This weblog application is built around the Post
model, which stores instances of blog posts.
Here you use the Rails scaffold generator to create the
model and its controller, as well as the index (list),
show, new, and edit views.
The generator also creates
a migration file for creating the model's database table,
and creates unit test and fixture stubs for
writing model tests.
In the Projects window, right-click the rubyweblog project node and
choose Generate from the pop-up menu.
-
In the Rails Generator dialog box, select scaffold from the Generate
drop-down list, as shown in the following figure.
-
Type Post in the Model Name text box.
Type title:string in the
Attribute Pairs
text box and click OK.
The Output window lists the files that
the scaffold generator creates and updates.
Creating the Database
In this section, you use a Rake task to create the
rubyweblog_development
database. Then you use the migration
file
to add the posts table to the database.
In the Projects window,
right-click the rubyweblog project node, and choose
Run/Debug Rake Task from the pop-up menu.
-
Type db in the Filter text box to narrow
the task list to just the db tasks, as shown
in the following figure.
-
Select db:create from the Matching Tasks list and click Finish.
Rake creates the database for the development configuration
as defined in the database.yml file.
Note: If you see error messages in the Output
window, verify that the user name and password in the development
section in the database.yml
file are correct. Also verify that your database server
is running.
In the Projects window, expand Database
Migrations and expand migrate.
Double-click the node for the migration class, which
will have a name that begins with a date and time
and ends with create_posts.rb.
The file opens to show the self.up method,
which creates a table called posts, and the
self.down method, which tears the posts table down,
as shown in the following code sample.
class CreatePosts < ActiveRecord::Migration
def self.up
create_table :posts do |t|
t.string :title
t.timestamps
end
end
def self.down
drop_table :posts
end
end
Note that the create_table method adds an id
column by default, and that the
timestamps method adds the created_at and
updated_at
columns to the database table.
-
In the Projects window, right-click the
rubyweblog node and choose
Migrate Database > To Current Version.
This action updates the the database to include the posts table.
The Output window indicates when the migration is complete,
as shown in the following figure.
Caution: Some users get an error that no rubyweblog_development database exists. It was not created by db:create despite a correct database.yml entry. The workaround is to create the rubyweblog_development database manually. You can use NetBeans IDE for this. In the Services window, right-click the node for your MySQL server and select Create Database. See Issue 167017.
Running the Application
Now test the application.
-
In the Projects window,
expand the Configuration node and
double-click routes.rb to open it in the editor.
-
Find the following comment.
# map.root :controller => "welcome"
-
Uncomment the line and change the controller to
"posts", as
shown next.
map.root :controller => "posts"
-
In the Projects window, expand the Public node,
right-click index.html and choose Delete
from the pop-up menu.
The index.html page displays a
default Welcome page, which is not what you want.
By deleting index.html, Rails looks
in routes.rb to determine which page
to display.
Choose File > Save All from the main menu.
-
Right-click the rubyweblog node and
choose Run from the pop-up menu.
This action starts the server
and displays the following page in the browser.
-
Click the New post link to display the second page
of the application,
as shown in the following figure.
-
Type a title and click Create.
The following figure shows a sample blog post.
Click the Back link to return to the
list of posts.
Adding Another Table Column
Here you add a body column to the posts table
to hold the text for each blog entry.
-
Right-click the Database Migrations node and
choose Generate from the pop-up menu.
The Rails Generator dialog box opens with migration
selected in the
Generate drop-down list.
-
Type
AddBodyToPost body:text in the Arguments
text box,
as shown in the following figure.
-
Click OK.
The IDE creates the versioned migration script. Its
name starts with a date and time and ends with
add_body_to_post.rb. The file opens to show
the self.up method, which adds a body column, and the
self.down method, which removes the column,
as shown in the
following code sample. Notice how the generated code
extracted the table
name from
the first argument AddBodyToPost.
class AddBodyToPost < ActiveRecord::Migration
def self.up
add_column :posts, :body, :text
end
def self.down
remove_column :posts, :body
end
end
-
Right-click the rubyweblog node and choose
Migrate Database > To Current Version from the
pop-up menu.
Alternatively, right-click in the source file and
choose Run
from the pop-up menu.
In the Projects window, expand Views, expand
posts, and double-click edit.html.erb to open the file
in the
editing area.
Add the statements shown in bold in the following
code sample to the edit.html.erb file.
Alternatively, place the cursor before the
<p> tag for the title field and drag the cursor
to the position after the paragraph's ending </p>
tag, then press Ctrl+Shift+Down Arrow to duplicate
the lines. Edit the duplicated statements as shown in the following
code.
<h1>Editing post</h1>
<% form_for(@post) do |f| %>
<%= f.error_messages %>
<p>
<%= f.label :title %><br />
<%= f.text_field :title %>
</p>
<p>
<%= f.label :body %><br />
<%= f.text_area :body %>
</p>
<p>
<%= f.submit "Update" %>
</p>
<% end %>
<%= link_to 'Show', @post %> |
<%= link_to 'Back', posts_path %>
Double-click new.html.erb to open the file in the
editing area.
Add the statements shown in bold in the following
code sample to the new.html.erb file. Alternatively, use
Ctrl+Shift+Down Arrow
to duplicate the title paragraph and edit the
duplicated statements as shown in the following code.
<h1>New post</h1>
<% form_for(@post) do |f| %>
<%= f.error_messages %>
<p>
<%= f.label :title %><br />
<%= f.text_field :title %>
</p>
<p>
<%= f.label :body %><br />
<%= f.text_area :body %>
</p>
<p>
<%= f.submit "Create" %>
</p>
<% end %>
<%= link_to 'Back', posts_path %>
Double-click show.html.erb to open the file in the
editing area.
Add the statements shown in bold in the following code sample
to the show.html.erb file.
Alternatively, use Ctrl+Shift+Down Arrow
to duplicate the Title paragraph as described in Step 6,
change Title: to Body:,
and change @post.title to @post.body.
<p>
<b>Title:</b>
<%=h @post.title %>
</p>
<p>
<b>Body:</b>
<%=h @post.body %>
</p>
<%= link_to 'Edit', edit_post_path(@post) %> |
<%= link_to 'Back', posts_path %>
Choose File > Save All
from the main menu.
Return to the browser and click the New post
link to see
the new body column, as shown in the following figure.
Create a few more blog entries.
When you have finished, click Back to return to the
"Listing posts" page.
Validating Input
Currently, users can add empty posts to the blog. Here
you modify the application to prevent blank posts. First,
you prepare the test database and
write a unit test to verify that users cannot
create a post unless it has a title and a body.
Next you add code to the Post class to require
that the users provide values
for both the title and the body fields. Last, you run
the unit test to verify that your modifications work
as intended, and then you run the application.
- In the Projects window, right-click the rubyweblog node and choose Run/Debug Rake Task from the pop-up menu.
- Type RAILS_ENV=test in the Parameters text box.
- Find and double-click the db:create entry to run the task to create the rubyweblog_test database.
Caution: The db:create function does not work for some users. In this case, run the db:create:all function. See Issue 167017.
- Once again, right-click the rubyweblog node and choose Run/Debug Rake Task from the pop-up menu.
-
Find and double-click the db:test:prepare entry. The IDE adds the Post table to your rubyweblog_test database.
-
In the Projects window, expand Test Files > unit and
double-click post_test.rb to open it in the
editing area.
-
Replace the contents of the file with the
following code.
require 'test_helper'
class PostTest < ActiveSupport::TestCase
def test_invalid_with_empty_attributes
post = Post.new
# An empty Post model should be invalid
assert !post.valid?
# The title field should have validation errors
assert post.errors.invalid?(:title)
# The body field should have validation errors
assert post.errors.invalid?(:body)
end
end
-
Right-click the rubyweblog project node and choose
Test from the pop-up menu.
The IDE runs all the project's unit tests
and displays the output in the Ruby Test
Results window, as shown in the following
figure. Because the application
allows empty posts, the unit test
for the Post model fails. Next
you modify the application to require
values for the Text and Body columns.

In the Projects window, expand the Models
node and double-click post.rb
to open the file in the editor.
Open a line inside the Class definition, type vp,
and press Tab.
The IDE replaces the vp trigger with the following parameterized code template.
validates_presence_of :attribute
-
Type title, :body, then press Enter.
The code should look like the
following statement.
validates_presence_of :title, :body
-
To retry your unit test to see if the
changes create the desired effect, right-click the
rubyweblog node and choose Test from the pop-up menu.
The PostTest passes, but some of the
PostController tests fail because of the
validation changes that you made
to the Posts model. You correct
this problem in the next two steps.
-
In the Ruby Test Results window, double-click the
test_should_create_post node to open that test
in the editing area.
-
Replace post :create, :post => {}
with the following code, which provides
values for the title and the body.
post :create, :post => { :title => "Nene",
:body => "Nenes are Hawaiian Geese" }
-
Scroll to the test_should_update_post
method and change the put call to
also pass in a title and a body, as shown
in the following code.
put :update, :id => posts(:one).id,
:post => {:title => "Nene", :body => "Are rare birds." }
-
To verify that the tests now pass, right-click in the
editing area and choose Test File from the pop-up menu.
The IDE runs the tests that are in the
PostsControllerTest class
and displays the output in the
Ruby Test Results window.
-
Return to the browser, click New post,
and click Create.
The application now reports that the title and body cannot
be blank, as shown in the following figure.

Making the List Look More Like a Blog
Here you edit the index.html view to make the blog list
look more like a typical blog, as shown in the following figure.
-
From the Projects window, expand Views > posts
and double-click index.html.erb to open
the file in the editing area.
This view shows the list of blog entries.
-
Delete the <h1> and <table>
elements, and replace them with the following code that is
shown in bold.
<h1>The Ruby Blog</h1>
<% for post in @posts %>
<h2><%= post.title %></h2>
<p><%= post.body %></p>
<small>
<%= link_to "permalink",
:action => "show",
:id => post %>
</small>
<hr>
<% end %>
For each instance of a post action, this
code produces a
title, body, and Permalink.
-
Save the changes and run the application to see the
new interface for the Post model.
-
To display the blog with the most recent entry first,
edit the code that you just added to reverse
the sort order by adding a call to the .reverse
method, as shown next.
<% for post in @posts.reverse %>
Save the file and refresh your browser to see the
list displayed
in reverse order.
Applying What You Have Learned
Using the skills that you have learned in this exercise, create
a task list web project. Use the scaffold generator to build
a scaffold around the Task model with title:string and
description:text fields. Use Rake to create the database, and
then use Database Migrations to create the table.
Don't forget to edit the route.rb file to map the root,
and remember to delete the index.html file.
Next Steps
>> More NetBeans Ruby Documentation
|
|