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

本文介绍了一种使用特定属性区分不同模型数据的方法,通过示例展示了如何在 Rails 中设置多态关联,包括创建表结构及定义模型间的关系。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值