Tuesday Oct 09, 2007

Generating Rails Models

Our NetBeans Ruby tutorials show how to use the Rails Generator dialog box to add models to a Ruby on Rails web application. We show one step that uses the Rails Generator wizard to create the following:

  • Model File: This file contains the model's unique methods and business rules.
  • Initial Migration Files: Migration file for creating the database table. You run the migration files to create and modify the database table, and to back out changes
  • Unit Text Files: Files for testing your development.

In the subsequent step we have you edit the migration file to specify the column names and types. Did you know that you can can create the model and edit the migration file in one step by passing arguments in the Rails Generator? For example, let's say that I wanted a categories database table. I can right-click the project's node and choose Generate. In the Rails Generator wizard, I choose model from the Generate drop-down list. Then, I enter the following text in the Argument text box, and click OK to create the files:

Category name:string description:text level:integer created:timestamp icon:binary

The arguments list begins with the model name and is followed by column-name:type parameters. The type can be one of :string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean. To learn more about model arguments, see the TableDefinition API.

After the IDE finishes creating the files, I can click on the create db/migrate/002_create_categories.rb link in the Rails Generator tab in the Output window to open the file in the editor. The contents looks like this:

class CreateCategories < ActiveRecord::Migration
  def self.up
    create_table :categories do |t|
      t.column :name, :string
      t.column :description, :text
      t.column :level, :integer
      t.column :created, :timestamp
      t.column :icon, :binary
    end
  end

  def self.down
    drop_table :categories
  end
end

Once you have a migration file set up, you can move your application to another machine and have the IDE create the tables automatically. The same is true for database changes. With the up and down methods, you can quickly add or back out changes. Migrations also make it easier to switch to a different database server, say from JavaDB to MySQL.

Note: If you have an existing database, and you want to quickly create migration files, right-click the project node and choose Run Rake Task > db > schema > dump. The IDE writes the schema for your database to Database Migration > schema.rb. You can copy the create statements from the schema dump into migration files.

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