Ruby/ActiveRecord/Assumption from ActiveRecord

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

ActiveRecord infers database table names based on class names.

It assumes the existence of certain database columns.
The first assumption of an Active Record class is the table name. 
In the case of our Account class, the table Active Record assumes is accounts. It makes this assumption based on the following guidelines:
The name of the table within the database is the pluralized name of the class defined in your Active Record program. 
The table name is in lowercase. 
If the class name includes multiple words that begin with capital letters, the words will be separated by underscores in the table name.
 
Examples of Active Record Table Pluralization
 
Class Name         Table Name
Account            accounts
Person             people
UserImage          user_images
Address            addresses
Currency           currencies
Mouse              mice
In addition, Active Record also assumes that each table has an automatically 
incremented integer primary key column named id.



id is default for autoincrease

=begin
drop database Contact;
create database Contact;
use Contact;
CREATE TABLE Employee (
   id  int unsigned not null auto_increment primary key,
   Name VARCHAR(50),
   Phone VARCHAR(15),
   departmentId int
);
 
CREATE TABLE Department(
   id    int unsigned not null auto_increment primary key,
   Name VARCHAR(50),
   Phone VARCHAR(15)
 
);
 
=end
require "rubygems"
require "activerecord"
ActiveRecord::Base.establish_connection(
  :adapter => "mysql",
  :host => "localhost",
  :username => "root",
  :database => "Contact")
class Employee < ActiveRecord::Base
   set_table_name "employee"
end
class Department < ActiveRecord::Base
   set_table_name "department"
end
account = Employee.new
account.save
account = Employee.find(1)
puts account.destroy



If you want table names to be singular instead of plural, you can set the configuration parameter pluralize_table_names:

ActiveRecord::Base.pluralize_table_names = false