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

本文介绍了一种通过在关联表中增加额外字段来实现带有数据的多对多关系的方法,并给出一个具体的订杂志示例,展示了如何创建订阅模型及定义自定义查询。

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

Many-to-Many Relationships with Extra Data 带有数据的多对多关系
一般多对多关系都带有 一个存储关系的表 这表一般用处比较单一 但是有时也需要在这个表中添加除关系以外的数据 下面有个订杂志的例子
一般情况下

def self.up
create_table :magazines do |t|
t.column :title, :string
end
create_table :readers do |t|
t.column :name, :string
end
create_table :magazines_readers, :id => false do |t|
t.column :magazine_id, :integer
t.column :reader_id, :integer
end





但是 这个:magazines_readers 表 在添加一些属性后就可以作为一个订阅模型使用
不再是单纯存储:magazines 和:readers 的关系 如下


def self.up
drop_table :magazines_readers
create_table :subscriptions do |t|
t.column :reader_id, :integer
t.column :magazine_id, :integer
t.column :last_renewal_on, :date
t.column :length_in_issues, :integer
end
end


三个模型的设置如下


class Subscription < ActiveRecord::Base
belongs_to :reader
belongs_to :magazine
end

class Reader < ActiveRecord::Base
has_many :subscriptions
has_many :magazines, :through => :subscriptions
end

class Magazine < ActiveRecord::Base
has_many :subscriptions
has_many :readers, :through => :subscriptions
end




定义自己的查询方法

class Magazine < ActiveRecord::Base
has_many :subscriptions
has_many :readers, :through => :subscriptions
has_many :semiannual_subscribers,
:through => :subscriptions,
#注意这里用source
:source => :reader,
:conditions => ['length_in_issues = 6' ]
end



例子
chad> ruby script/console
>> Magazine.find(1).semiannual_subscribers
=> [#<Reader:0x26ba05c @attributes={"name"=>"Anthony Braxton", "id"=>"1"}>]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值