1. Using Rails Active Record - Models
Rails Active Records - Models is the Object Relational Mapping (ORM)
that comes with Rails; in which tables, rows and columns map respectively
to classes, objects and object attributes. Rails Active Records gives
an interface to manage databases table via Ruby programs.
Each (row) Active Record object has CRUD (Create, Read, Update,
and Delete) methods for database as we have in other relational databases
such as MySQL.
2. Matching ROR domain model to SQL
A Ruby program requires some specific notations to
understand queries. We have then to adapt SQL notations to
ROR ones following certain rules:
a. An entity "X" for which a table is built and its database
have the same name in the plural (Xs).
b. Each entity has a field called id, that is a unique integer
to record that entity into a table.
c. If an entity "Y" belongs to an entity "X", then table "Y" has
a field called X_id.
d. Capitalize and use the singular form for the name of
models.
3. Creating Active Record files
We will create the Active Record files for the entities "hydrocarbons"
and "groups"for "organics" application.
use the generate tool and issue the following command lines:
C:\ruby\organics\> ruby script/generate model Hydrocarbon
and:
C:\ruby\organics\> ruby script/generate model Group
We get: this results.
The generator has created models called Hydrocarbon, and
Group and stored instances of hydrocarbons and
groups.
Among the files created by the generator, we haveRails migration
that can be used to create quickly database tables and columns.
In the subdirectory C:\ruby\organics\app\models, the files
hydrocarbon.rb and group.rb have been created; that contain
repectively:
class Group < ActiveRecord::Base
end
and
class Hydrocarbon < ActiveRecord::Base
end
For hydrocarbon.rb, set some privileges:
class Hydrocarbon < ActiveRecord::Base
belongs_to :group
validates_presence_of :compound
validates_presence_of :formula
validates_numericality_of :nbCarbons, :message=>"Error Message"
end
For: group.rb:
class Group < ActiveRecord::Base
has_many :hydrocarbons
end
|