corner imagecorner image
FeaturesPluginsDocs & SupportCommunityPartners

Creating a Ruby Weblog in 10 Minutes

Contributed by Brian Leonard, maintained by Chris Kutler
June 2008
[Revision number: V6.1-2]

Note: The current release is NetBeans IDE 6.5. If you are using NetBeans IDE 6.5, see Creating a Ruby Weblog in 10 Minutes: NetBeans IDE 6.5..

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

Contents

Content on this page applies to NetBeans IDE 6.1

To complete this tutorial, you need the following software.

Software or Resource Version Required
NetBeans IDE with Ruby support Version 6.1
MySQL database server Version 5.0
Rails framework 2.0

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.

  1. In the NetBeans IDE, choose File > New Project.

  2. Select Ruby from the Categories list and Ruby on Rails Application from the Projects list, as shown in the following figure.

    Selecting a Ruby on Rails project type in the New Project wizard
  3. Click Next to name the project and specify its location.
  4. Type rubyweblog in the Project Name text box, as shown in the following figure.

    Accept all the other default settings on this page.

    Setting the Project Name to rubyweblog in the Name and Location step
  5. Skip to the Step 8 if the following conditions apply:

    • You are using the default root user name
    • The root does not require a password
    • You are using the MySQL database server

    The IDE assumes these conditions by default.

  6. Click Next to configure the database access.

  7. Select the Specify Database Information Directly option, select the Database Adapter, and type the User Name and Password. Leave the Database Name blank.

  8. 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.

  9. Verify that the development section's adapter, database, user name, and password settings are correct, then click the small x button in the database.yml tab to close the file.

    Image of the database.yml 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.

  1. In the Projects window, right-click the rubyweblog project node and choose Generate, as shown in the following figure.

    Choosing the Generate action from the pop-up menu
  2. In the Rails Generator dialog box, select scaffold from the Generate drop-down list, as shown in the following figure.

    Selecting scaffold from the Generate drop-down list
  3. Type Post in the Model Name text box.

  4. 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 001_create_posts.rb migration file to add the posts table to the database.

  1. In the Projects window, right-click the rubyweblog project node, and choose Run Rake Task > db > create from the pop-up menu.

    Choosing create from the pop-up menu.

    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.

  2. In the Projects window, expand Database Migrations and expand migrate.

  3. Double-click the 001_create_posts.rb node to open the file in the editing area, as shown in the following figure.

    double-clicking the 001_create_posts.rb node

    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.

  4. In the Projects window, right-click the rubyweblog node and choose Migrate Database > To Current Version, as shown in the following figure.

    Migrating the database

    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.

    Migration messages in the Output window

Running the Application

Now test the application.

  1. In the Projects window, expand the Configuration node and double-click routes.rb to open it in the editor.

  2. Find the following comment.

    # map.root :controller => "welcome"
  3. Uncomment the line and change the controller to "posts", as shown next.

    map.root :controller => "posts"
  4. 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.

  5. Choose File > Save All from the main menu.

  6. Click the Run Main Project button in the toolbar.

    Run Main Project button

    This action starts the WEBrick server, which is a web server (written in Ruby) that is provided as part of the Ruby on Rails framework, and displays the following page in the browser.

    Page in web browser

    Note: You can configure the project to use a different server. If you are using a server other than WEBrick, you might need to type http://localhost:3000/posts in the browser's address text box and press Enter.

  7. Click the New post link to display the second page of the application, as shown in the following figure.

    Second page of application in browser
  8. Type a title and click Create.

    The following figure shows a sample blog post.

    Sample blog post
  9. 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.

  1. Right-click the Database Migrations node and choose Generate from the pop-up menu.

    Choosing Generate from pop-up menu

    The Rails Generator dialog box opens with migration selected in the Generate drop-down list.

  2. Type AddBodyToPost body:text in the Arguments text box, as shown in the following figure.

    Generate Migration dialog box
  3. Click OK.

    The IDE creates the versioned migration script 002_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
  4. 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.

  5. In the Projects window, expand Views, expand posts, and double-click edit.html.erb to open the file in the editing area.

  6. 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 and drag the cursor 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.

    <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 %>
  7. Double-click new.html.erb to open the file in the editing area.

  8. 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 code as described in Step 6.

    <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 %>
  9. Double-click show.html.erb to open the file in the editing area.

  10. 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 %>
  11. Choose File > Save All from the main menu.

  12. Return to the browser and click the New post link to see the new body column, as shown in the following figure.

    New post with body column
  13. Create a few more blog entries.

    When you have finished, click Back to return to the "Listing posts" page.

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.

  1. In the Projects window, expand the Models node and double-click post.rb to open the file in the editor.

  2. 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
  3. Type title, :body, then press Enter. The code should look like the following statement.

    validates_presence_of :title, :body
  4. Save the file, return to the browser, click New post, and click Create.

    The application now reports that the title and body cannot be blank.

    Error reporting missing title and body

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.

Revised blog page
  1. 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.

  2. 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 %>
    
    <br />
    
    <%= link_to 'New post', new_post_path %>
    

    For each instance of a post action, this code produces a title, body, and Permalink.

  3. Save the changes and run the application to see the new interface for the Post model.

  4. 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 %>
  5. 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