作为java中的O/R Mapping的使用者来说,看到rails中的activeRecord的实现后不禁汗颜,原来O/R Mapping可以如此简单。
我反复看过几遍activeRecord的文档,觉得其灵活之处不亚于hibernate,而且简单实用。
现作笔录如下:
1.关联
n:1: belongs_to: XXXX
1:n: has_many:XXX
1:1: has_one :XXX
m:n: has_and_belongs_to_many:XXX
连接join: :through => :XXX (for ex:has_many :photos :through => :slides) rails 1.1才有此功能
特殊关联:
acts_as_list :列表
acts_as_tree :父子关系
acts_as_nested_set
class Slide < ActiveRecord::Base
belongs_to :slideshow
acts_as_list :scope => "slideshow_id"
belongs_to :photo
end
表示sildes表中的slideshow_id为belongs_to :slideshow关系中的外键(FK)
class Category < ActiveRecord::Base
acts_as_tree
end
2.级联
has_many :XXX, dependent => true
3.设定主键:rails不支持复合主键,rails默认数据表中的主键名称为id,如果您的主键不为id,如下设置:
class Photo < ActiveRecord::Base
set_primary_key "created_at"
end
4.domain中的继承关系
class Photographer < Person
end
class Person < ActiveRecord::Base
end
5.domain中的组件关系
CREATE TABLE people (
id INT AUTO_INCREMENT NOT NULL,
type VARCHAR(20),
name VARCHAR(20),
email VARCHAR(30),
street_address VARCHAR(30),
city VARCHAR(30),
state VARCHAR(20),
zip INTEGER(5),
camera VARCHAR(20),
PRIMARY KEY (id)
);
class Person < ActiveRecord::Base
composed_of :address, :class_name => "Address",
:mapping => [[:street_address, :street_address],
[:city, :city],
[:state, :State],
[:zip, :zip]]
end
class Address
def initialize(street_address, city, state, zip)
@street_address = street_address
@city = city
@state = state
@zip = zip
end
attr_reader :street_address, :city, :state, :zip
end
6.查找记录
find_by_<column_name> find_by_id
find_by_<column_name>_and_<column_name> find_by_name_and_email(name, email)
7.验证字段有效性
class Photo < ActiveRecord::Base
validates_presence_of :filename 验证是否为空
end
validates_format_of :email,
:with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
validates_length_of :name, :within => 6..100
8.事务处理
def transfer(from, to, amount)
Account.transaction do
from.debit(amount)
to.credit(amount)
end
end
posted on 2006-09-14 15:55
老妖 阅读(4959)
评论(0) 编辑 收藏 所属分类:
rails