feiyang10086 发表于 2011-10-21 14:19

Ruby on Rails 表间关联

Ruby on Rails 表间关联



1 创建外键

       t.integer : 表名单数 _id

       关联表的命名要以首字母的顺序决定如 categories_products

       关联表的联合索引:add_index:categories_products,[:product_id,:category_id]2 模型对象中指定关联

       一对一关联belongs_to:order has_one:invoice一对多关联belongs_to:order has_many:ling_items多对多关联has_and_belongs_to_many:products3 belongs_to 声明(当前对象有一个父对象)

       belongs_to 接受一个 hash 参数: ( 如果改变关联名称 )

            :自定义父对象属性名,

:父对象类名 (:class_name) ,

:外键名 (:foreign_key) ,

:条件 (:conditions)

具有下列方法: .product 返回关联对象

                                 .product=obj 设置关联对象

                                 .build_product(attributes{}) 新建一个关联对象

                                 .create_product(attributes{}) 新建并保存一个关联对象

4 has_one() 声明(当前对象有一个子对象)

       has_one 接受一个 hash 参数:(除 belongs_to 的参数还有)

            : dependent => 值为:

                     : destroy 删除父记录的同时删除子表的关联记录

                     : nullify 删除父记录之后留下子记录,同时将记录外键置 null

                     : false   删除父记录时不改变子记录的任何

具有下列方法: .invoice 返回关联对象

5 has_many() 声明

       接受一个 hash 参数(包括 has_one 的所有键值对)

            :order=>”xxx,yyy DESC”查询时按照 xxx , yyy 降序得到数组

       具有下列方法: .orders 返回关联对象.orders.replace() 替换为新的一组 orders 对象 .orders.destroy_all.orders.clear 解除所有关联(把外键置为 NULL )

                                 .orders.find() find 方法与所有的 find 方法一样

6has_and_belongs_to_many() 声明

       具有前面的所有参数和方法

7 把模型类映射成为连接表

       在不作为连接表的模型中除了加入 has_many: 被作为连接表的模型复数,还要加入一个 has_many: 与之进行实际关联的模型复数 , :through=>:readings

       与 has_many 可以改变关联名称如:

       has_many: 自定义的关联名称复数 , :through=>xxx , :source=>: 实际关联的模型(注意不是复数 )

       当通过关联模型表找到的数据可能是多条一样的这里通过在 has_many 的后面在加入一个参数来去掉重复 :unique=>true 这是在 ActiveRecord 中实现的;若在数据库中则在 has_many 中要加入查询条件参数 :select=>”distinct users.*”

8 扩展关联(既关联时加入关联的条件)

       在 has_many 后加入语句块并定义一个给条件时的关联查找 如:has_many :articles, :through=>:readings do

       def rated_at_or_above(xxxx)

            find :all, :conditions=>xxxxend

end

       用时:good_articles=user.articles.rated_at_or_above(xxxx)共享关联方法时则把方法放入模块中然后在 has_many 后家如参数

:extend=> 模块名称

9 连接多张表

1 )单表集成(用于属性重复率比较高的模式)

       一张数据库表中存有说有继承与被集成的属性字段

       继承时只要在模型首部标记 Customer<Person 等

       对于继承之间的关联只需要在表中设置好关联的字段,在用 belongs_to 的自定义方法来定义与被继承之间的关系

2 )多态关联(用于属性重复率比较少的模式)

       每个多态一张表

       在引用多态的模型的表中建立外键 关联名 _id ,关联名 _type 两个字段;模型中则 belongs_to : 关联名 , :polymorphic=>true 注: polymorphic 表示多态

       在每个多态模型中建立 has_one : 引用此多态的模型名 , :as=>: 关联名

       用时:引用多态的模型 . 关联名 = 某一个多态对象

2gua 发表于 2011-10-21 15:33

哟,这个鼓励啊。
页: [1]
查看完整版本: Ruby on Rails 表间关联