Creating a Rails 2.0 Ruby Weblog in 10 Minutes

THIS TUTORIAL IS FOR NETBEANS IDE 6.0. IF YOU ARE USING NETBEANS 6.1, SEE THE UPDATED TUTORIAL ON THE NETBEANS RUBY TRAILS PAGE.

Note: On 2/25/08, I updated Code Sample 3 to take advantage the REST URLs and Path methods that the map.resources entity in the routes.rb generates. I also modified Step 3 in the last Doing More section to match the modified code.

Our Ruby weblog tutorial series for NetBeans IDE 6.0 is written for Rails 1.2.5 and uses the ActionController scaffold method. The Rails 2.0 framework dropped this method, so the tutorials do not work if you have updated to Rails 2.0.

We are now learning about the 2.0 changes so that we can produce updated tutorials. In the meantime, here is a quick draft of how to do the first weblog tutorial, Creating a Ruby Weblog in 10 Minutes, using the Rails 2.0 framework and the NetBeans 6.0 IDE. We are still learning about the new Rails 2.0 features, so there will probably be many changes to come. Please consider this a temporary document.

Currently, this tutorial assumes that you are using a native Ruby interpreter, and have updated to Rails 2.0 (I believe you need to update RubyGems as well). There are many flavors of Ruby, one of which can be download from ww2.ruby-lang.org. To learn how to set up the IDE to use a native Ruby interpreter, see Installing and Configuring Ruby Support.

Note: This tutorial uses the MySQL database server. See Installing and Configuring Ruby Support for information about using a MySQL database server in a Ruby application that is built using the NetBeans 6.0 IDE.

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 in the Categories field and Ruby on Rails Application in the Projects field. Click Next.

    Note: The first time that you create a Ruby project in the IDE, the IDE checks if you have any other Ruby installations in addition to the bundled JRuby software. If you do, the IDE displays a dialog box asking you to select which software to use. Choose the native Ruby interpreter.

  3. Type rubyweblog in the Project Name field. Accept all the other default settings.
  4. Click Finish to create the new project.

    The IDE creates the project directory with the same name as your project.

Configuring the Database Environment

The next step is to edit the file database.yml, which is already configured to use the MySQL adapter and the development database. You do not need to do any configuration unless the root user requires a password.
  1. In the editing area, edit the database.yml by providing the password in the development configuration.
  2. Save and close the database.yml file.

    Note: If your operating system's host file does not contain localhost, use 127.0.0.1 instead.

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

Creating the Scaffold

Here you use the Rails Generator to create a scaffold and a model for the application. The rubyweblog application requires a Post model for storing instances of blog posts.

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

  2. In the Rails Generator dialog box, choose scaffold from the Generate drop-down list.

  3. Type Post title:string in the Model Name field and click OK (Controller Name and Actions not valid arguments in Rails 2.0).

    The Rails Generator creates a model named Post, creates a migration file, and adds the controller and views for listing, creating, updating, and deleting posts. In addition, Rake edits the routes.rb file to map Post as a resource. The Output window lists the files that are created as part of the model generation.

Migrating the Database

The file that you work with next is the migration file, 001_create_posts.rb.
  1. In the Output window, click the link for the db/migrate/001_create_posts.rb file.

    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

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

    Note that Rails 2.0 provides some new db Rake tasks, such as create (which you used earlier), drop, reset, rollback, and version.

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. Expand the Public node, right-click index.html and choose Delete.

    index.html 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.
  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.

Doing More: Adding Another Field

Here you add another field so that, in addition to the Title field, the posts table includes a Body column for providing the text of the blog.

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

    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. Choose File > Save All.
  3. 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.
  4. Typically, you would now edit the views to add the new field. For this tutorial, you will simply regenerate the scaffold. In the Projects window, right-click the rubyweblog project node and choose Generate.

  5. In the Rails Generator dialog box, choose scaffold from the Generate drop-down list.

  6. Type Post title:string body:text --skip-migration in the Model Name field.

  7. Select the Overwrite radio button.

  8. Click OK.

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

  10. 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 3: Code for index.html.erb
    <h1>The Ruby Blog</h1>
    
    <% for post in @posts %>
      <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.

  2. Run the application to see the new interface for the Post model.

  3. To display the blog with the most recent entry first, reverse the sort order by adding .reverse to the end of @posts in index.html.erb:

    	  <% for post in @posts.reverse %>
    	  

    Save the file and refresh your browser to see the list displayed in reverse order.

Comments:

Nice. Three comments:
1. view files are named .html.erb and not .rhtml.erb as you are showning.
2. The browswer does not start automatically when I run the program for some reason. I have to run the browser manually. I am on a windows machine - InstantRails and NB 6 combination.
3. The last step (3) says list.rhtml instead of index.html.erb.
More 2.0 conversions in works?
Bharat

Posted by Bharat Ruparel on January 16, 2008 at 09:24 AM PST #

Where's the video?

Posted by anon on January 16, 2008 at 11:22 PM PST #

Excellent tutorial. As with Bharat, I too have just downloaded NetBeans and InstantRails and have just begun playing with Rails.

While Netbeans has definitively come a long way, there is one thing that is troublesome. The code insight is very clumsy so far. Currently you cannot change the speed and some of the suggestions that it gives are plausible.

Other than that, I manged to get through the tutorial just fine and I'm enjoying my Rails experience.

Posted by rip747 on January 18, 2008 at 04:01 AM PST #

Bharat, Thanks for catching those mistakes. I just posted an update with the fixes.

rip747, you might want to get involved in some of the threads going on in the dev@ruby.netbeans.org alias in regards to code completion and quick fixes. Your suggestions and input are of value. For example, see http://ruby.netbeans.org/servlets/ReadMsg?list=dev&msgNo=1054. To learn more about participating in the NetBeans Ruby Community, see http://wiki.netbeans.org/wiki/view/RubyCommunityInformation.

This blog talks a bit about how you can get involved: http://blogs.sun.com/divas/entry/how_do_you_rubh

Posted by Diva #2 on January 18, 2008 at 05:00 AM PST #

Hello there,
I want to integrate JSF with JRuby on rails.
For example ,i have a jsp page and in this page i have a hyperlink that the Text property is Blog and when user click on it go to the blog that was created with JRuby on Rails.
Is it possible?
If it is possible ,what i must do?

Thanks
Khosro.

Posted by Khosro on January 19, 2008 at 01:02 AM PST #

When I do the rake task for this project after first page of tutorial and create a .WAR file, deploy it to the Glassfish/Sun Application Server from the JDK kit, I just get a directory listing from the application server. Could one of you complete the tutorial by deploying it to the application server?

Posted by D Moore on January 19, 2008 at 04:37 AM PST #

Khoso,

I have never tried this and thus can not give any advice. My first guess would be to deploy both projects to a GlassFish server and link to the blog from the JSP page.

D Moore and Khoso, here are some resources for learning about deploying a Ruby project to a GlassFish server.

http://www.netbeans.org/kb/60/ruby/setting-up.html#glassfish
http://blogs.sun.com/arungupta/entry/jruby_on_rails_netbeans_and

If you have questions or problems deploying the Ruby project to the GlassFish server, I highly recommend posting them to either the glassfish alias (https://glassfish.dev.java.net/servlets/ProjectMailingListList) or the users alias at ruby.netbeans.org (http://wiki.netbeans.org/wiki/view/RubyCommunityInformation).

Hope this helps,

Chris

Posted by Diva #2 on January 19, 2008 at 06:06 AM PST #

Amazing tutorial for someone new to rails.

Posted by David Tay on January 20, 2008 at 12:10 PM PST #

在最后的"Doing More"里用下面的代码更加符合REST和Rails2:
In the last "Doing More", the code like following would be more RESTful and Rails2ful:
<%= link_to 'Permalink', post_path(post) %>

Posted by maninred on January 22, 2008 at 02:54 AM PST #

Thanks Manired, I appreciate this information.

Posted by Diva #2 on January 22, 2008 at 03:19 AM PST #

Good tutorial. Keep the good work and post more tutorials on rails 2.0.

Posted by Naru on January 29, 2008 at 12:41 AM PST #

Great "how to" - thanks so much for taking the time - I have been playing with Ruby for several weeks (and love it) - I now love it even more due to the NetBeans IDE - and now ... with Rails, it is just amazing. Thanks so much!!!

Ashley

Posted by Ashley on January 30, 2008 at 11:03 AM PST #

(1) After this step "Type Post title:string in the Model Name field and click OK (Controller Name and Actions not valid arguments in Rails 2.0)." I get following error "wrong constant name Title:stringController" in Rails Generator window.

(2) I'm also not sure on how to start the MySQL database server.

(3) I'm using NetBeans 6.0.1 & Rails 1.2.5 on Windows XP Pro.

(4) I had previously upgraded to Rails 2.0.2 and got some obscure errors so I reinstalled the programs from scratch and left Rails at 1.2.5

Thanks in advance

Posted by cosmo on February 11, 2008 at 07:53 PM PST #

Cosmo,

If you are using Rails 1.2.5, then follow the tutorial at http://www.netbeans.org/kb/60/ruby/rapid-ruby-weblog.html. The mini-tutorial in this blog entry uses new features of 2.0.2 that are not available in 1.2.5.

To learn how to start the database server, see http://dev.mysql.com/doc/refman/5.0/en/windows-start-command-line.html

Posted by Diva #2 on February 11, 2008 at 11:31 PM PST #

Thanks.

(1) I have already tried that example. It looks the same as this example up to the point of the error.
(2) I have retried with the MySQL server running and correct database name (not sure if this matters or not). In any case, get the same error in same spot.
(3) The error occurs before anything "fancy" starts to happen in the example.
(4) So I'm still confused.

Cheers.

Posted by cosmo on February 12, 2008 at 04:44 PM PST #

Hope you got your problem resolved Cosmo. I am new to Ruby and RoR so I started with the new InstantRails 2.0. The problem with starting new at this point in time is that the tutorials are still for the 1.2. The errors you see I think are from using the 1.2 version installed with NetBeans. Try installing InstantRails then change your Ruby interpreter (Tools > Options, Ruby, Platform Tab) to C:InstantRails-2.0-win\\ruby\\bin\\ruby.exe.
I think that simply starting InstantRails will start your MySQL automatically but I don't really know that for sure. All I know is it just works.

Posted by Bill Thayer on February 13, 2008 at 02:29 AM PST #

Cosmo,

This tutorial will NOT work with 1.2.5. You say "It looks the same as this example up to the point of the error."

This is not true. In the 1.2.5 version at http://www.netbeans.org/kb/60/ruby/rapid-ruby-weblog.html, following the Configure the Database Environment, is a section called "Creating the Model". In that section you GENERATE the MODEL.

In this 2.0 version of the tutorial, you skip this step, as you can now generate the model at the same time that you GENERATE the SCAFFOLD.

Please use the http://www.netbeans.org/kb/60/ruby/rapid-ruby-weblog.html tutorial with your 1.2.5 Rails. If you have problems completing this tutorial, there is a feedback button at the bottom of the tutorial, so that we can communicate.

Posted by Diva #2 on February 13, 2008 at 02:52 AM PST #

What if we want to create our tables in MySQL and not through Ruby? How can we do scaffolding in this case?

Posted by Cheri on March 06, 2008 at 02:21 AM PST #

Cheri,

Just don't run the migrations.

Posted by guest on March 07, 2008 at 03:41 AM PST #

Hi,

It is very good tutorial, I was just wondering how do you include reply with each thread of topics (title)? any idea?

Hery

Posted by Hery Rakoto on March 12, 2008 at 12:32 AM PDT #

I am not understanding what you mean by a thread of topics. Do you mean like replies in a forum? Can you point to an example of a blog with replies. We do have a tutorial (part 2 of this series) that shows how to add comments (like this blog has). This has not yet been updated for Rails 2.0, but I hope to have an update done next week. You can see the original at http://www.netbeans.org/kb/60/ruby/model.html

Posted by diva #2 on March 12, 2008 at 02:24 AM PDT #

Thank you for the tutorial. What I'm stuck on now is how in Rails 2.0 to allow the user to perform a search to look for and display, for example, a post containing the word "dog"? This whole REST approach makes adding additional methods to the controller a nightmare!!!

Cheri

Posted by Cheri on March 12, 2008 at 02:57 AM PDT #

I'm using Netbeans 6.0.1 with jruby 1.0.3 and rails 2.0. Also using javaDB.

I can create the Post model and get it to add new posts, as per the tutorial, but when I edit an existing post I get:

ArgumentError in PostsController#update

wrong # of arguments(2 for 1)

RAILS_ROOT: /home/jmvidal/share/progs/Blog
Application Trace | Framework Trace | Full Trace

/home/jmvidal/share/bin/netbeans-6.0.1/ruby1/jruby-1.0.3/lib/ruby/gems/1.8/gems/activerecord-2.0.2/lib/active_record/transactions.rb:129:in `rollback_active_record_state!'
/home/jmvidal/share/bin/netbeans-6.0.1/ruby1/jruby-1.0.3/lib/ruby/gems/1.8/gems/activerecord-2.0.2/lib/active_record/transactions.rb:108:in `save_with_transactions'
/home/jmvidal/share/bin/netbeans-6.0.1/ruby1/jruby-1.0.3/lib/ruby/gems/1.8/gems/activerecord-2.0.2/lib/active_record/base.rb:2034:in `update_attributes'
app/controllers/posts_controller.rb:63:in `update'
app/controllers/posts_controller.rb:62:in `update'

Any ideas?

Posted by Jose M Vidal on March 13, 2008 at 05:52 AM PDT #

I was able to get through all three parts of the tutorial once I had the help of this first part. Just keep the right name of the controller in mind and all the rest of it is easy to figure out.
This is the first time I've used an IDE in years. It's really intuitive and the vim plug-in makes it a REAL winner for me. I'm running it on a small windows laptop with xampp--but I'm going to put it on my Mac and Linux boxes as well. Thanks so much! Looking forward to getting into Rails and NetBeans.

Posted by Alan on March 13, 2008 at 03:13 PM PDT #

The following step does not work for me:

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.
Note that Rails 2.0 provides some new db Rake tasks, such as create (which you used earlier), drop, reset, rollback, and version.

---instead, I get "rake aborted, connection refused -- connection refused" in the output window.

Any assistance would be truly appreciated.

Posted by John Sands on June 10, 2008 at 07:45 AM PDT #

Hi Alan,

Did you do this step?

"In the editing area, edit the database.yml by providing the password in the development configuration."

Are you sure you are providing the correct password? What happens when you try to log in MySQL using the username and password that you provided in the database.yml?

Posted by diva#2 on June 10, 2008 at 07:58 AM PDT #

Great tutorial! My first tutorial with rails and I love it! Thanks!

Posted by Ryan on July 01, 2008 at 10:08 AM PDT #

Thanks Ryan.

You can find more tutorials in this series at http://www.netbeans.org/kb/trails/ruby.html, including an even more RESTful version of this tutorial (the 6.1 versions).

Posted by diva#2 on July 01, 2008 at 10:54 AM PDT #

I tried the tutorial, it was very good, well.... up to the point where I executed the WebRick server.
Webrick started OK, however when the browser (Firefox 2.0.14) started, it showed an error page, besides the fact that the url that appeared in the browser was http://localhost:3000 instead of http://localhost:3000/posts that the tutorial indicated.

After that I tried to manually update the url (adding "posts" at the end). Firefox just showed a grey screen showing no error at all.

Finally while WebRick was running I tried to start another browser instance (Opera this time) and I added manually the URL http://localhost:3000/posts.

Surprisingly it worked!

Question...what can be wrong?
Does anybody has experienced this problem before?

Best Regards
Carlos

Posted by Carlos on July 03, 2008 at 02:14 PM PDT #

Hi Carlos,

Look at the section titled "Running the Application". Is the map.root statement uncommented? Did you change "Welcome" to "posts"?

Did you delete the index.html from the public folder shown in Step 3?

Let me know.

Posted by guest on July 03, 2008 at 02:32 PM PDT #

Thanks for putting this together.

I'm getting this message when trying to add the text field:

The name 'PostsHelper' is either already used in your application or reserved by Ruby on Rails.
Please choose an alternative and run this generator again.

Posted by someone on July 28, 2008 at 01:41 PM PDT #

Someone,

Can you be more specific about the step number you were on when you saw this message?

By the way, there is a much newer and better version of this tutorial at http://www.netbeans.org/kb/61/ruby/rapid-ruby-weblog.html

- Chris

Posted by diva#2 on July 28, 2008 at 01:50 PM PDT #

With the PostHelper error, I got this when doing the section Doing more: Adding Another Field. In order to get past this I had to delete
posts_helper from under Helpers. Once deleted I was able to generate the scaffold.

This is all I had in the posts_helper:
module PostsHelper
end

Posted by DezDiggler on August 19, 2008 at 03:41 AM PDT #

DezDiggler,

You don't say what error you got. Are you still using NetBeans 6.0 and Rails 2.0? If so, can you describe the error that you got?

If you are using NetBeans 6.1 then there is a link at the top of the blog that takes you to the version of this tutorial that works for 6.1. If you are using NetBeans 6.5 then take a look at http://blogs.sun.com/divas/entry/getting_started_with_netbeans_ruby1

Posted by diva#2 on August 19, 2008 at 04:03 AM PDT #

Cheri,

Does this help: http://wiki.rubyonrails.org/rails/pages/HowToImplementSearch

Posted by guest on August 26, 2008 at 02:10 AM PDT #

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

divas

Search

Archives
« April 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
   
       
Today