前面的
tagging一文中说道acts_as_taggable插件依赖于Rails的多态关联特性,今天我们就来看看它
有时候一个表和多个表关联,比如people和company都有address,我们可以利用Rails的多态关联来实现其功能
(其实我觉得标题应该改为Polymorphic Associations - belongs_to :whatevers才对)
1,Migrations
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
我们在addresses表加上addressable_id和addressable_type这两个字段而不是加上person_id或company_id来作为外键关联
2,Models
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
我们通过addressable来代替Person或Company或whatever,并且指明polymorphic为true
我们可以这样来建立关联:
person = Person.create(...)
address = Address.create(...)
address.addressable = person