NetBeans 6.1 Draft: Creating a Rails 2.0 Weblog in 10 Minutes

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.

Tutorial Requirements

This tutorial requires the following technologies and resources.

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. Click Next.

  3. Type rubyweblog in the Project Name text box. Accept all the other default settings on this page.

  4. Click Next.

  5. Select Specify Database Information Directly.

  6. Leave the Database Name text box blank, the IDE will create default development, test, and production database names based on the project name.

  7. Type root in the User Name text box.

  8. If the root user requires a password, type the password in the Password text box.

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

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

  1. In the Projects window, right-click the rubyweblog project node and choose Generate.

  2. 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).

  3. Type Post in the Model Name text box.

  4. Type title:string in 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.

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

  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.

    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.

    Code Sample 1: Code for 001_create_posts.rb
    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.

    This action updates the the database to include the posts table. The Output window indicates when the migration is complete.

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. Find the comment:

    # map.root :controller => "welcome"
    	
  2. Add the following line under the comment.
    map.root :controller => "posts"
    	
  3. In the Projects window, expand the Public node, right-click index.html and choose Delete.

    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 figure out what page to display.

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

  5. 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:3000 in the browser's address text box and press Enter.

  6. Click the New post link to display the second page of the application.

  7. Enter a title and click Create.

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

  1. Right-click the Database Migrations node and choose Generate. In the Rails Generator dialog box, type AddBodyToPost body:text in 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.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.

    Code Sample 2: Code for 002_add_body_to_post.rb
    class AddBodyToPost < ActiveRecord::Migration
      def self.up
        add_column :posts, :body, :text
      end
    
      def self.down
        remove_column :posts, :body
      end
    end

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

  3. In the Projects window, expand Views and expand posts.

  4. Double-click edit.html.erb to open the file in the editing area.

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


  6. Double-click new.html.erb to open the file in the editing area.

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


  8. Double-click show.html.erb to open the file in the editing area.

  9. 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 %>


  10. Choose File > Save All.

  11. Return to the browser and click the New Post link to see how Ruby recognizes the new body column.

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

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

  2. Open up a line inside the Class definition, type vp, then press Tab.

    The IDE replaces the vp trigger with the following code template.
    validates_presence_of :attribute
  3. Type title, :body. The code should look like the following statement.
    validates_presence_of :title, :body
  4. 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

  1. 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 index.html.erb
    <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 post action, 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.

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

  3. 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 below.

    <% @posts.reverse.each do |post| %>
    	  
  4. Save the file and refresh your browser to see the list displayed in reverse order.
Comments:

Hello Chris,
Everything works. In "Creating the Database" section, step 3 you wrote:
"Note that the create_table method adds a post_id column by default..."
Instead of "post_id", you should write "id" since that is what happens.
Regards,
Bharat

Posted by Bharat Ruparel on March 16, 2008 at 09:38 PM PDT #

Thank you Bharat Ruparel for the correction. I made the fix.

Posted by diva #2 on March 17, 2008 at 03:24 AM PDT #

This is already out of date. I can't believe it! Adding a scaffold in the latest build of RoR 2.0 with the latest build of Netbeans 6.1 is very flawed.
There is no "attribute pairs" field. The fields it asks for are "Model Name", "Controller Name" and "Actions". RoR automatically adds the controller name and if you put one into Netbean's scaffold generation field, it will spit back a "wrong number of arguments" field. Also, adding db names like title:string in the actions field will not add anything to the schema as this tutorial says. The comments are useless. However, adding the words Create Destroy Show and Edit to the Actions field will indeed work. This tutorial needs to be updated!

Posted by Mitch on March 23, 2008 at 03:22 PM PDT #

Mitch,

Is it possible the you forgot to select scaffold from the drop-down list. I think that is why you are seeing Model Name, Controller Name, and so forth. If you skipped step 2, the dialog box defaults to the controller generator.

I modified this blog entry to emphasize that you need to select the scaffold generator and I added a screenshot. Hope this helps.

Posted by diva#2 on March 24, 2008 at 05:09 AM PDT #

Mitch,

Upon further investigation, I see that the scaffold generator that you describe sounds like the old (pre Rails 2.0) version that is in NetBeans 6.0 (and 6.0.1). Click Help > About in the main toolbar and verify that it says NetBeans IDE 6.1.

Posted by diva#2 on March 24, 2008 at 05:56 AM PDT #

I jumped the gun with my first comment and I'm sorry for the tone of my comment. I got so frustrated with just starting to learn RoR, realizing the update to 2.0 made all previous tutorials useless and not realizing I needed to install the Beta Netbeans when I thought I had the latest already installed AND being disappointed with the your buggy and slow as molasses competition \*cough\* Aptana \*cough\*.

Posted by Mitch on March 24, 2008 at 08:37 AM PDT #

No problem Mitch. Good luck with your learning path. I have just started to work on part 2 (building relationships) and it will be awhile before I get that one out.

Posted by guest on March 24, 2008 at 10:16 AM PDT #

Post a Comment:
Comments are closed for this entry.
About

divas

Search

Archives
« July 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
  
       
Today