Friday Aug 15, 2008
Friday Aug 15, 2008
Now that I have most of the online help done for NetBeans Ruby 6.5, I can start updating the tutorials. I have already started getting comments from customers who are discovering that the 6.1 tutorials don't work with 6.5, so I thought I should quickly blog about known differences. The main reasons these tutorials don't work with 6.1 are: (1) Rails upgrade from 2.0.2 to 2.1 and (2) the addition of the GlassFish server. I am still learning about the 6.5 changes and enhancements, so I probably won't get them all listed here. If you find something that I didn't catch, please add a comment.
Installing and Configuring Ruby Support
The GlassFish V3 Prelude application server is now included with the Ruby bundle. If you are starting from a fresh install, it will be the default server. When you run your Rails apps using the GlassFish server, the URL will be different than if you run with WEBrick or Mongrel. The port is 8080 and you include project name in the URL. (There is an option in the JRuby tab of the server's properties dialog box to Deploy All Rails Applications at Root Context, so if you don't want the project name in the URL you could change that configuration. However, you can have problems if you have more than one Rails application deployed to the server if they have similar routes.).
For the information about Using Database Servers With JRuby, I suggest that you go to wiki.netbeans.org/FaqRailsJRubyDatabaseAccess. If you are using the generic Active Record JDBC adapter and you select the Access Database Using JDBC checkbox, the IDE puts the appropriate driver in the classpath for you, providing that the database server has been registered with the IDE and the IDE knows the driver's location. If you are running the application with the GlassFish server, and you are using SQLite (or a database server that stores its databases in files), you have to edit the database.yml file to specify the full path to the database, such as
database: /usr/local/sqlite/var/rubyweblog_development.sqlite
Now that GlassFish V3 is included, you can run with GlassFish for your development, test, and production environments. The IDE now uses Warbler instead of Goldspike. If you select the Add Rake Targets to Support App Server Deployment, and you don't have the Warbler gem installed, the New Project wizard forces you to go all the way to the last step, where you can click a button to install Warbler.
Getting Started With Ruby and Rails
With Ruby applications, the concept of a "main" project doesn't apply anymore. If you click the Run Project button in the main toolbar, the IDE runs the current project. To see what the current project is, look in the IDE's title bar. I typically right-click the project's node in the Project window and choose Run project, because that way I don't have to think about which of my open projects is current.
If you are using Rails 2.1.0 (The Bundled JRuby comes with Rails 2.1.0), you need to edit the Configuration > initializers > new_rails_defaults.rb file. Find the two lines that start with ActiveRecord::Base and comment them out. Supposedly, in the next Rails release, this code will only be executed if active record is defined, but for now, you have to comment out the lines.
In Step 7 of Create the Model Class, you paste some code into the item.rb file. In that code, replace this line:
DATA_FILE="data.yml"
with this line:
DATA_FILE = RAILS_ROOT + "/data.yml"
The original code won't work when you run in the GlassFish server, because it relied on the server running in the working directory.
In Step 8 of of Run the Application (for the Rails project), use the X button that appears in the left side of the server's tab in the Output window. While there is also an X button in the bottom right for the WEBrick server, this button does not appear for the GlassFish server. On the other hand, the X button is in all the server output windows.
In Step 9 of Run the Application , there is no longer a "main" project for Ruby projects. So, click the Run Project button if the title bar shows that your Rails application is the current project, or right-click the project's node and choose Run.
Creating a Ruby Weblog in 10 Minutes
In the Creating the Database section, you now choose Run/Debug Rake Task, which opens the Rake Runner. Type db:c in the Filter text box to narrow down the list of tasks. Double-click db:create to run that task.
In step 3 of Creating the Database section, you will see that the file name has changed. Instead of using a sequence number prefix (as in 001_create_posts.rb), the Rails script used a timestamp prefix (something like 200808152345453_create_posts.rb). To learn more about why Rails did this, see Brent's blog entry about timestamp based migrations.
As mentioned earlier, when you run the Rails application with the GlassFish app server, the URL uses 8080 as the port and includes the project name, such as http://localhost:8080/rubyweblog/.
In Step 6 of Adding Another Table Column, the code that is generated for Rails 2.1 looks a little different. You can either copy and paste what is provided in the tutorial, and which still works, or you can duplicate the lines as explained in the step and replace both instances of :title with :body, and replace text_field with text_area as shown below.
<p>
<%= f.label :body %><br />
<%= f.text_area :body %>
</p>
Do the same as above for new.html.erb.
Wednesday Aug 06, 2008
Monday Jul 21, 2008
As I mentioned a couple of weeks ago, I am researching the new Ruby and Rails features in the upcoming NetBeans IDE 6.5. Last week, Martin Krauskopf and I talked about the work that he is doing. Some of you might know Martin from his earlier work with Jesse Glick on NetBeans Module Development (also known as APISupport) which was great experience for him. Before he joined Sun, Martin says that he "enjoyed a short experience working on the Vim plugin for Eclipse ;)".
One of his most noticeable pieces of work for 6.5 is the new Rake Runner dialog box, which I am finding to be a nice improvement. In addition, Martin has also done an overhaul on the Rake infrastructure, and he worked on providing a pre-generated Rakefile for new projects, which includes tasks such as clean, gem, packages, rdoc, spec, and test (Martin: thanks Dudley Flanders for tips).
On the debugging side, he has released new versions of the fast JRuby debugger and ruby-debug-ide gems, which the 6.5 IDE utilizes to bring support for conditional breakpoints and catchpoints (breakpoint on exception).
You will also see improvements in the Ruby Gems Manager. When you open up the manager, you can now easily switch the platform, without having to wait for the manager to finish fetching the data for the currently selected repository. Martin also added the -a (fetch all versions) and -d (fetch detailed gem description) options for tweaking gems fetching so that it goes a bit faster. If the manager finds that it doesn't have permissions on the repository directory for updating and installing gems, it will now invoke the underlying gem commands using gksu or kdesu, as appropriate (if it finds it).
Two other changes that Martin made were to (1) provide support for Rubinius, an addition to MRI Ruby and JRuby, and (2) Enable you to use the project's Properties dialog box to pass JVM options to JRuby, such as
For 6.5, if time permits, he would also like to add support for the Rubinius fast debugger that is being developed by Adam Gardiner, and polish some problems and behaviors of all debuggers generally, since there are still a few remaining issues after the ruby-debug-ide overhaul.
I asked Martin what he does when he isn't working so hard. He likes to spend his free time doing sports such as skiing and biking. He usually spends his vacations with his girlfriend and their friends traveling in his own country (Czech Republic), or around the world, often in the mountains with backpacks. His best vacation was the trip to Himachal Pradesh in the north-west of India.
Tuesday Jul 15, 2008
I just published two more NetBeans IDE 6.1 tutorials.
Getting Started With Ruby and Rails is a quick tutorial that shows off many of the NetBeans features.
Using Java Libraries in Rails Applications shows to use the Java API in Rails applications. In this tutorial, you use the FreeTTS speech synthesis Java libraries to enable users to listen to blog posts. I have fun testing this tutorial and listening to the funny sounding man in my computer read my blogs to me. I got quite a bit of help and advice from NetBeans Ruby users for the final bits of code. Thanks for the help guys! I do appreciate it.
Tuesday Jul 08, 2008
One of the software engineers that I get to work with on the NetBeans Ruby project is Erno Mononen, who works in Prague. Erno works mostly on the NetBeans Ruby IDE, but is also involved in some parts of the Java EE support in the NetBeans IDE. I am finally catching up with the documentation for 6.1 and took some time to talk with Erno about the work that he is doing for the upcoming 6.5 release.
Chris: The new Test Runner UI that you recently added to the 6.5 development version is awesome. Can you tell us about other cool changes that you are making to the next version of Ruby support?
Erno: Thanks! I'll be looking into adding support for Warbler, which offers a more elegant way to create a .war file out of a Rails application than the currently supported GoldSpike plugin. I'd also like to implement a couple of enhancements in the database and server integration areas, such as adding support for additional servers. And last but not least, there is still a lot to do in the test runner -- I've gotten some very good ideas from our users, and would like to address as many of those as possible for 6.5.
Chris:You mention ideas from users. How do users submit ideas to the NetBeans Ruby engineering team?
Erno:There are several different ways to do that. Users can file enhancement requests directly into our issue tracker or they can send their ideas to the dev@ruby.netbeans.org or users@ruby.netbeans.org mailing lists, where they can be discussed with the community. Furthermore, most of the developers in the Ruby team have blogs that are open for comments. Lastly, we welcome anyone to come to have a chat if you see us around at conferences or anywhere else. Feedback is always appreciated.
Chris: Can you give examples of user suggestions that you have incorporated into the product?
Erno: I think the new test runner serves as a good example both of a user requested new feature and smaller enhancement. It was our users who requested this in the first place, so the test runner as a whole is a user requested feature that has been incorporated into the product. In addition, since its incorporation our users have been active in filing bugs and enhancements for it. For example, the error badges for failing tests in the test tree view of the runner were suggested by a user.
Chris: Can you talk about some of the 6.5 features that you think Ruby programmers will look forward to seeing?
Erno: Hopefully the new test runner will be one of those features :^) There are quite a few other things as well that I think our users may find of interest, to mention a few of them:
In addition there are a lot of improvements in JavaScript, Ruby, and CSS editing, and naturally a bunch of bug fixes in all areas.
Chris: So what do you do when you are not working on the IDE?
Erno: I spend most of my free time with my wife and son, but when I have some time just for myself, I can usually be seen either doing various sports, reading books, or playing the guitar.
Chris: Thanks Erno, I look forward to writing about the new NetBeans Ruby features for 6.5.
Notes: You can download Milestone 1 (a pre-beta version) of NetBeans IDE 6.5 from www.netbeans.org. The Ruby Trails web page has links to Erno's blog as well as the other engineers who work on the NetBeans Ruby IDE. The NetBeans Ruby Wiki page has links to the most recent entries of all these blogs. Also, you can view the NetBeans Ruby mailing lists at Nabble.
Monday Jul 07, 2008
Over the last year, as I wrote and updated the Ruby tutorials, I end up with many different versions of the Rails applications, where each is based on a different version of JRuby. I often test with both Ruby and JRuby, and I try to test them using different database servers. Rather than follow a tutorial from scratch to get a working version for my current configuration, I wanted to learn how to easily take an application and change it to work with a different database configuration. For example, how can I take an application that I developed using the native Ruby interpreter, and make it work using the JRuby interpreter, or take an MySQL application and use it with a PostgreSQL server. As I researched the history of JRuby access to databases, I compiled my notes into a FAQ, which I posted to wiki.netbeans.org/FaqRailsJRubyDatabaseAccess.
Hopefully, you will find it helpful. If not, post a comment as to what other information you would like to see, or let me know when the instructions don't work. Even better, you can correct the FAQ itself if you have joined the NetBeans community.
Friday Jun 20, 2008
Accessing the IRB Console from the IDE
The Ruby support in the NetBeans 6.1 IDE includes the Interactive Ruby (IRB) Console. To open the console, choose Window > Other > Ruby Shell from the main menu. The console opens in the bottom window.

The interpreter that is used by the console depends on the main project's Ruby Platform setting (the bold project node in the Projects window is the main project). To see the Ruby Platform setting, right-click on project's node and choose Properties. If your project is a Ruby project, select Run in the Categories pane to see the Ruby Platform setting. You can switch to a different platform, if you want.
The tab for the IRB console window indicates which the interpreter it is using. In the above screenshot, you can see that the IDE is using the Built-In JRuby platform.
To exit from the IRB console, type exit or quit, and close the window.
Using Gems in the IRB Console
Before you can use gems in the IRB, you have to load RubyGems. Most platforms take care of this for you. For those that do not, such as the built-in JRuby platform, you must load it yourself. If you do not load RubyGems, you will see an error similar to the following output.
>> require 'renum'
LoadError: no such file to load -- renum
from (irb):2:in `require'
from (irb):2:in `signal_status'
The quickest way load RubyGems is to type the following statement in the console.
>>
require 'rubygems'
If you do not want to type that every time you open an IRB console, you can
add -rubygems to the Ruby Options text box in the
project's Properties dialog box.

Using .irbrc Files for Common
Settings
Another way to load RubyGems every time you open the console, is to add or
copy over an .irbrc file to the project's top level folder and add
require 'rubygems' to that file. To create an .irbrc
file, right-click the project node and choose New >
Other from the pop-up menu. Select Other in the
Categories pane, select Empty File in the
File Types pane, and click Next. Name the
file .irbrc and click Finish.
If you have IRB settings that you would like applied to all your projects,
such as loading RubyGems, you can put the settings in an .irbrc
file in your home directory. In order to get the IDE to read this file when
opening the IRB console, you must create a HOME system environment
variable (be sure to make it all capital letters) that provides the path to
your home directory, and restart the IDE.
Note that you will not see the .irbrc file in the Projects
window or the Files window. To learn how to configure the IDE so that you can
see this file, see MRHAKI's blog
that shows how.
Using the JRuby IRB Console
The IDE also offers support for the JRuby IRB console. With this console, you get code completion, as shown below. You can type the first few characters and press Tab to see a list of suggestions.

The JRuby IRB console also has a history feature. Pressing the Up-Arrow key scrolls through through the command history and pressing the Down-Arrow key scrolls back. You can press Return to re-execute a command.
To enable the JRuby IRB console, add the following flag to your NetBeans IDE
startup command or add it to the netbeans_default_options entry in
the netbeans-install-dir/etc/netbeans.conf file, and
restart the IDE. One problem with this option, is that you get the JRuby IRB
console, regardless of which platform your project is using.
-J-Dirb.jruby=true
Tuesday Jun 10, 2008
For the past few weeks, I have been working on writing the NetBeans IDE 6.1/Rails 2.0 version of the Building Relationships Between Models tutorial. The NetBeans Ruby community provided helpful guidance, especially Florian Gilcher, who spent a lot of time shaping up the code and teaching me about best practices. Florian moderates the Rails part of Rubyforen.
The first input I got from Florian was actually about the Rails 1.2 version of the tutorial. In this tutorial, they used the flash to pass the post's id from the show action to the show template and from the show template to post_comment action.
Florian pointed out that using the flash to store state information can cause two severe bugs:
Session Time Out Bug. A session is volatile and thus gets erased after a certain amount of time, typically 15 minutes after the last client request. Should a user get a phone call in the middle of writing a comment, the session could be invalidated, creating a new one. When the user submits the comment, the flash is empty and he gets a 500 status. Not good!.
Multiple Request Bug. The flash holds for one unspecified request. If the browser fires off another request, the flash is emptied. Thus a user switching between writing a comment and reading posts on other message boards runs into the same problem as above.
I have the feeling that several of the lab participants at our JavaOne hands-on-lab ran into these exact problems, as they were using the same browser to read the lab steps and run the application. I had not run into these problems when testing the lab or the original tutorial. As Florian pointed out, "The bad thing about both bugs is that they almost never appear in testing environments. I would never sit before my PC writing plain text for 15 minutes, and explain my boss that I was testing ;)."
Instead of using the flash, you can simply add the the id in the call to form_tag (form_tag :action => 'post_comment', :id => @post). This maps to /blog/post_comment/id, which matches the pattern declared by the map.connect ':controller/:action/:id' mapping in routes.rb. An alternative is to pass it in a hidden field. One problem with these solutions is that the data can be tampered with, so you need to make your application able to cope with that. As Florian said, "If the user wants to play madman, he should only be able do this with data he actually is allowed to edit."
So, lesson learned! Fortunately, the NetBeans Ruby 6.1 tutorials use RESTful resources, and thus eliminate this bad practice altogether.
Friday Jun 06, 2008
Today, we published an updated version of the Building a Relationship Between Two Models tutorial. This update takes the RESTful approach to working with has_many relationships, in this case the relationship between a post (the parent) and its comments (the children). REST, which is an acronym for representational state transfer, is an architecture style for hypermedia, such as web applications. By using this architecture, you end up with a simple, uniform way to set up routing for your create-read-update-delete (CRUD) applications, which typically perform the following actions for a resource:
With RESTful routing, you can use a combination of four HTTP methods (GET, POST, PUT, and DELETE) and four patterns (/controller-name, /controller-name/:id, /controller-name/:id/edit, and /controller-name/new) to formulate the URLs that map to the above actions. For example, for the post resource, you can use the following URLs and HTTP methods:
The Rails support for RESTful routing makes this all very easy. When you add a resource to your Rails application, the framework automatically adds to the routes.rb file a map.resource method call that generates the appropriate route mappings to the seven actions, and also creates numerous helper methods for generating paths and urls in string and hash format. Basically, all you have to remember are four substrings:
For example, to generate the path to invoke the create action, you use new_post_path. To generate the path to invoke the edit action, you use edit_post_path(:id).
In the scenario in the tutorial, where there is a parent-child relationship, you use the Rails nested resources support, which ensures that the comment resources are always accessed in relationship to a post. For example, to generate the path to the create action for comments, you use post_comments_path(:post_id), which generates the URL /posts/:post_id/comments.
The tutorial is a nice way to quickly see RESTful routing in action. If you are interested in learning more about this topic, the tutorial lists several resources that provide in depth explanations of REST architecture and Rails support for this methodology.
Note: I should point out that REST architecture is not simply about URLs and routing. It is a set of constraints that "when applied as a whole, emphasizes scalability of component interactions, generality of interfaces, independent deployment of components, and intermediary components to reduce interaction latency, enforce security, and encapsulate legacy systems." [Roy Fielding, Architectural Styles and the Design of Network-based Software Architectures, Chapter 5, 2000].
Tuesday Apr 08, 2008
This year, Brian Leonard, and I (diva #2) are putting on the Developing (J)Ruby on Rails Applications with the NetBeans™ IDE hands-on lab at JavaOne. If you haven't tried developing a web application using Ruby on Rails, this is a good opportunity to get your feet wet. For those of you who are familiar with Ruby but haven't tried it in the IDE, you will also find this lab helpful. In this lab, you build the classic Ruby web log, you access the FreeTTS Java API to speach-enable the application, and you deploy the application to the GlassFish application server.
Speaking of JavaOne, in last year's hands-on-lab, one of the exercises was to use Dynamic Faces to build a chat room application. This section has been turned into the Building an Ajax Chat Room with the Ajax Transaction Dynamic Faces Component tutorial which is available from the NetBeans Web Application Learning Trail.
About the picture. Right behind me is flowing lava. To be able to walk right up to 1200 degree Celsius lava flow was an awesome experience. Fortunately, because the lava contains a large amount of glass, the lava flows very slowly.
Wednesday Mar 26, 2008
The Ruby Developer Resource Center at developers.sun.com is live. Just learning or already deploying? Get downloads, docs, news feeds, blogs, screencasts, and learning trails to help you build applications using Ruby, JRuby, and Ruby-on-Rails.
Monday Mar 17, 2008
I know that many of you NetBeans Ruby users blog about your experiences. Here's a chance to win a $500 gift certificate or a NetBeans T-Shirt. If you have blogged about your NetBeans 6.1 IDE experience, all you have to do is go to this Blog Contest page and submit the URL to your blog. Do it before April 18, 2008.
Friday 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.
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.
rubyweblog in the Project Name text box.
Accept all the other default settings on this page.
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.
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).
Post in the Model Name text box.
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.
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.
Rake creates the MySQL database for the development configuration in the database.yml file.
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
|
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.
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"
map.root :controller => "posts"
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.
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.
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.
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: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
|
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.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 %>
|
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 %>
|
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 %> |
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.
Here, you add code to the Post class to ensure that the users provide values for both the title and the body fields.
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
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.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.
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 below.
<% @posts.reverse.each do |post| %>
Tuesday Jan 15, 2008
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.
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.
rubyweblog in the Project Name field.
Accept all the other default settings. Click Finish to create the new project.
The IDE creates the project directory with the same name as your project.
database.yml by providing the password in the development configuration.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.
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.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.
In the Projects window, right-click the rubyweblog project node and choose Generate.
In the Rails Generator dialog box, choose scaffold from the Generate drop-down list.
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.
001_create_posts.rb.
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
|
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.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"
map.root :controller => "posts"
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.
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.
Click the New post link to display the second page of the application.
Enter a title and click Create.
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.
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
|
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.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.
In the Rails Generator dialog box, choose scaffold from the Generate drop-down list.
Type Post title:string body:text --skip-migration in the Model Name field.
Select the Overwrite radio button.
Click OK.
Return to the browser and click the New Post link to see how Ruby recognizes the new body field.
Create a few more blog entries.
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
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.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.
Run the application to see the new interface for the Post model.
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.