每天一剂Rails良药之Polymorphic Associations - has_many :whatevers

前面的[url=http://hideto.iteye.com/blog/75917]tagging[/url]一文中说道acts_as_taggable插件依赖于Rails的多态关联特性,今天我们就来看看它
有时候一个表和多个表关联,比如people和company都有address,我们可以利用Rails的多态关联来实现其功能
(其实我觉得标题应该改为Polymorphic Associations - belongs_to :whatevers才对)

1,Migrations
[code]
class AddPeopleCompanyAndAddressTables < ActiveRecord::Migration
def self.up
create_table :people do |t|
t.column :name, :string
end
create_table :companies do |t|
t.column :name, :string
end
create_table :addresses do |t|
t.column :street_address1, :string
t.column :street_address2, :string
t.column :city, :string
t.column :state, :string
t.column :country, :string
t.column :postal_code, :string
t.column :addressable_id, :integer
t.column :addressable_type, :string
end
end

def self.down
drop_table :people
drop_table :companies
drop_table :addresses
end
end
[/code]
我们在addresses表加上addressable_id和addressable_type这两个字段而不是加上person_id或company_id来作为外键关联

2,Models
[code]
class Person < ActiveRecord::Base
has_many :addresses, :as => :addressable
end
class Company < ActiveRecord::Base
has_many :addresses, :as => :addressable
end
class Address < ActiveRecord::Base
belongs_to :addressable, :polymorphic => true
end
[/code]
我们通过addressable来代替Person或Company或whatever,并且指明polymorphic为true
我们可以这样来建立关联:
[code]
person = Person.create(...)
address = Address.create(...)
address.addressable = person
[/code]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值