G0574's Archiver

弯月圆刀 发表于 2008-7-25 14:57

Understanding Polymorphic Associations

activeRecord中的associations比较容易理解。

比如:一个作者有许多帖子,author has_many posts。

这种关联从数据库角度来描述,就是posts表中有一个字段author_id,通过这个外键来建立这种联系。

当你查询时:author.posts时,实际上的SQL语句可能是:select * from posts where posts_id = author.id.

可见这个纽带就是foreign key。

但是对于Polymorphic,这个纽带不仅仅是foreign key还有一个model类型(class 的名称)。举例来说:


有一个addresses(地址)表格,可以和users(用户)表和orders(订单)表关联。为了让其他model来关联,addresses必须暴露一个接口,[code]
class Address < ActiveRecord::Base
  belongs_to :addressable, :polymorphic => true
end
[/code]这个接口就是addressable。

现在User就可以通过这个接口来关联:[code]class User < ActiveRecord::Base
  has_one :address, :as => :addressable
end
[/code]反映在数据库的表中。addresses的结构如下:[code]  addresses
  ---------
  street
  city
  country
  addressable_id  
  addressable_type # <- is a string
[/code]当然rails会有必要的migration让这些字段自动产生:[code]create_table :addresses do |t|
  t.string :street
  t.string :city
  t.string :country
  t.references :addressable, :polymorphic => true
end
[/code]背后的真相是:[code]bob = User.find(7)
bob.address        
# SELECT * FROM addresses WHERE (addresses.addressable_id = 7 AND addresses.addressable_type = 'User')

order_17 = Order.find(17)
order_17.address         
# SELECT * FROM addresses WHERE (addresses.addressable_id = 17 AND addresses.addressable_type = 'Order')
[/code]

页: [1]

Powered by Discuz! Archiver 6.1.0  © 2001-2007 Comsenz Inc.