JavaScript Editor Free JavaScript Editor     JavaScript Debugger 




Main Page

Previous Page
Next Page

13.4. A Problem Revisited

Now that I've got some kind of idea (yeah, right) of what I'm doing with Ruby on Rails, the next question is how to use it in an application. The first task is to identify exactly what I want to do. For example, let's say that I want to display the items contained in the item table. The first necessary task is to generate a data model using the command console, as shown in Figure 13-8.

Figure 13-8. Generating a data model at the command prompt


The next step is to update the database.yml in the config directory to use the MySQL database from the previous chapters. The following is a snippet of the necessary code.

development:
  adapter: mysql
  host: localhost
  database: ajax
  username: root
  password: wyvern

These are the subsequent steps:

1.
Generate a controller for the item data model (see Figure 13-9).

Figure 13-9. Generating a controller for the data model at the command prompt


2.
Add a single line to the generated controller (See Listing 13-1).



Listing 13-1.

class ItemController < ApplicationController
  scaffold :item
end

3.
Fire up WEBrick to see what happens (see Figure 13-10).

Figure 13-10. A "Doh!" moment accessing a database


Hmm, not exactly what I expected. It seems that Rails changed the table name item to items. Not good. Being among the lazy, I decided to go into the MySQL Query Browser and change the table name from item to items (see Figure 13-11) and try again (see Figure 13-12).

Figure 13-11. Changing the database name in MySQL


Figure 13-12. A working example


That is a little closer to what I am looking for. The trick is that, by default, Rails generates a query assuming that item is the row and items is the table. This isn't a big deal; it is just something to keep in mind when creating tables and using the defaults.

But what if you don't want to use the stuff generated by default, and where does Ajax fit into things?

The answer to the first question is simple enough: Just generate a scaffold, as Figure 13-13 shows.

Figure 13-13. Generating a scaffold at the command prompt


It is then necessary to add the logic to the controller, the view, the layout, and the various templates.

This leaves only one question unanswered: Ajax? Remember the javascripts folder under the public folder? Well, in there is a file named prototypes.js that has all the logic required for asynchronous JavaScript and XML in Ruby on Rails. If you're interested, I'll offer a hint: Look at the xml_http_request? method. There's a lot to it, and I recommend playing.


Previous Page
Next Page




JavaScript Editor Free JavaScript Editor     JavaScript Debugger


©