`
tes
  • 浏览: 7656 次
  • 性别: Icon_minigender_1
  • 来自: 济南
最近访客 更多访客>>
社区版块
存档分类
最新评论

《Rails Recipes》Part II Database Recipes 知识点总结 三

阅读更多
Polymorphic Associations—has_many :whatevers Problem
《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



分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics