Polymorphic Associations—has_many :whatevers Problem
《Rails cookbook》中有一节和这一章类似
通过表中特定的属性区别不同模型的数据实现多态
数据库代码
模型关系设置
《Rails cookbook》中有一节和这一章类似
通过表中特定的属性区别不同模型的数据实现多态
数据库代码
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
#主要是由下面两个字段区别不同的mode,hibernate中也有类似的功能
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
模型关系设置
#注意:as和:polymorphic参数
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