NetBeans 6.1 Draft: Creating a Rails 2.0 Weblog in 10 Minutes
By divas on Feb 29, 2008
April 8, 2008 Update: The final version of this tutorial is available at http://www.netbeans.org/kb/61/ruby/rapid-ruby-weblog.html.
This is an early draft of a NetBeans IDE 6.1 tutorial in which you use the Ruby support in the NetBeans IDE to create and run a simple Rails 2.0 web application. This tutorial is an update of an earlier blog, which was written for NetBeans IDE 6.0. A final version of this tutorial will be published at www.netbeans.org when final NetBeans IDE 6.1 is released.
This tutorial requires the following technologies and resources.
- MySQL database server.
- NetBeans IDE 6.1 development build with Ruby support. A beta release is available from here.
Creating the Ruby on Rails Project
You begin by creating a Ruby on Rails project. By default, the application is created in a directory structure that conforms to the Ruby on Rails project conventions for applications.
- In the NetBeans IDE, choose File >
- Select Ruby from the Categories list and Ruby on Rails Application from
the Projects list. Click Next.
rubyweblogin the Project Name text box. Accept all the other default settings on this page.
- Click Next.
- Select Specify Database Information Directly.
- Leave the Database Name text box blank, the IDE
will create default development, test, and
production database names based on the project name.
- Type root in the User Name text box.
- If the root user requires a password, type the password
in the Password text box.
- 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. Notice that the default database name for the development configuration is rubyweblog_development.
- Click the small x button in the database.yml tab to close
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. Last, the generator adds the map.resources :posts declaration to the routes.rb file to create named routes that are mapped to the URL paths for the controller actions.
In the Projects window, right-click the rubyweblog project node and choose Generate.
In the Rails Generator dialog box, select scaffold from the Generate drop-down list. Make sure that you select scaffold, and not use the default selected value (controller).
Postin the Model Name text box.
title:stringin the Attribute Pairs text box, as shown in the following figure, 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
001_create_posts.rb migration file
to add the Posts table to the database.
- In the Projects window, right-click the rubyweblog project node, and choose
Run Rake Task > db > create.
Rake creates the MySQL database for the development configuration in the database.yml file.
- In the Projects window, expand Database
Migrations and expand migrate.
Double-click the 001_create_posts.rb node to open the file in the editing area.
The file opens to show the
self.upmethod, which creates a table called posts, and the
self.downmethod, which tears the posts table down, as shown in the following code sample.
Code Sample 1: Code for
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.
Running the Application
In the Projects window, expand the Configuration node and double-click
routes.rbto open it in the editor. Find the comment:
# map.root :controller => "welcome"
- Add the following line under the comment.
map.root :controller => "posts"
In the Projects window, expand the Public node, right-click index.html and choose Delete.
index.htmlpage displays a default Welcome page, which is not what you want. By deleting
index.html, Rails looks in
routes.rbto figure out what page to display.
- Choose File > Save All from the main menu.
Click the Run Main Project button in the toolbar.
This action starts the WEBrick server, which is part of the Ruby on Rails framework, and launches the web browser.
If you are using a server other than WEBrick, you might need to enter
http://localhost:3000in the browser's address text box and press Enter.
Click the New post link to display the second page of the application.
Enter a title and click Create.
Click the Back link to return to the list of posts.
Doing More: Adding Another Table Column
Here you add a body column to posts table to hold the text for each blog entry.
Right-click the Database Migrations node and choose Generate. In the Rails Generator dialog box, type
AddBodyToPost body:textin the Arguments text box and click OK.
The IDE creates the versioned migration script
002_add_body_to_post.rb. The file opens to show the
self.upmethod, which adds a body column, and the
self.downmethod, 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.
Code Sample 2: Code for
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.Alternatively, right-click in the source file and choose Run File from the pop-up menu.
- In the Projects window, expand Views and expand
- Double-click edit.html.erb to open the file in the
Add the statements shown in bold in the following code sample.
Alternatively, place the cursor before the <p> tag for the Title and drag the mouse to the position after the paragraph's ending </p> tag, then press Ctrl+Shift+Down Arrow to duplicate the lines. Replace Title with Body and replace f.text_field :title with f.text_area :body.
Code Sample 3: Adding the Body to the Edit View
<h1>Editing post</h1> <%= error_messages_for :post %> <% form_for(@post) do |f| %> <p> <b>Title</b><br /> <%= f.text_field :title %> </p> <p> <b>Body</b><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
Add the statements shown in bold in the following code sample. Alternatively, use Ctrl+Shift+Down Arrow to duplicate the Title paragraph and edit the duplicated code as described in Step 5.
Code Sample 4: Adding the Body to the New View
<h1>New post</h1> <%= error_messages_for :post %> <% form_for(@post) do |f| %> <p> <b>Title</b><br /> <%= f.text_field :title %> </p> <p> <b>Body</b><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
Add the statements shown in bold in the following code sample. Alternatively, use Ctrl+Shift+Down Arrow to duplicate the Title paragraph as described in Step 5, change Title: to Body:, and change @post.title to @post.body.
Code Sample 5: Adding the Body to the Show View
<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.
Return to the browser and click the New Post link to see how Ruby recognizes the new body column.
Create a few more blog entries.
Doing More: Validating Input
Here, you add code to the Post class to ensure that the users provide values for both the title and the body fields.
- In the Projects window, expand the Models node and double-click post.rb
to open the file in the editor.
Open up a line inside the Class definition, type vp, then press Tab.The IDE replaces the vp trigger with the following code template.
- Type title, :body. The code should look like the
validates_presence_of :title, :body
Run the application, click New Post, and click Create.The application now reports that the title and body cannot be blank.
Doing More: Making the List Look More Like a Blog
Expand Views > posts and open
index.html.erb,which is used to show the list of blog entries. Delete the <h1> and <table> tags and replace them with the following code that is shown in bold.
Code Sample 6: Code for
<h1>The Ruby Blog</h1> <% @posts.each do |post| %> <h2><%=h post.title %></h2> <p><%=h post.body %></p> <small><%= link_to 'Permalink', post %></small> <hr> <% end %> <br /> <%= link_to 'New post', new_post_path %>
For each instance of a
postaction, this code produces a title, body, and Permalink.
Notice that the second parameter for link_to is post. You might remember that when you generated the scaffold, the generator added a map.resources :posts declaration to the routes.rb. The resources method generates named routes for the Post model, one of which is post. The post named route produces the same result as passing :action => 'show', :id => post to the link_to method. The post id is passed in the URL. When you click the Permalink link, look at the URL in the address bar. You should see a URL similar to http://localhost:3000/posts/1.
To see all the named routes for a project, right-click the rubyweblog project node and choose Run Rake Task > routes. The Output window shows the route list. The first column shows the named route, the second and third columns show the HTTP verb and URL that are passed in the request, and the last column shows the controller and action that will be called. To learn more about using named routes see the Rails API for the ActionController:Resources class.
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
.reversemethod, as shown below.
<% @posts.reverse.each do |post| %>
- Save the file and refresh your browser to see the list displayed in reverse order.