每天一剂Rails良药之具有数据的多对多关系

每天一剂Rails良药之Many to Many Relationships Where the Relationship Itself Has Data

通常我们面临多对多时的处理方法是建立一个关系表,然后has_and_belongs_to_many
如果我们的关系表有其他属性,我们通过声明join table来放置关系表的其他属性
而当关系表本身具有其他属性时,我们可以通过join model来处理
如Magazine和Reader的多对多关系表Subscription:
[code]
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 :subscriptions do |t|
t.column :magazine_id, :integer
t.column :reader_id, :integer
t.column :last_renewal_on, :date
t.column :length_in_issues, :integer
end

end
[/code]
我们建立了magazines、readers和关系表subscriptions的migration,其中关系表中有两个一般属性
然后我们可以这样定义它们三者的model:
[code]
class Subscription < ActiveRecord::Base
belongs_to :magazine
belongs_to :reader
end

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

class Reader < ActiveRecord::Base
has_many :subscriptions
has_many :magazines, :through => :subscriptions
end
[/code]
这样我们通过Subscription这个join model建立了Magazine和Reader的多对多关系
[code]
magazine = Magazine.create(...)
reader = Reader.create(...)
subscription = Subscription.create(...)
magazine.subscriptions << subscription
reader.subscriptions << subscription
subscription.save
[/code]
这样我们就保存了一个Subscription对象我们可以通过magazine.readers或者reader.magazines查看关联的对象
我们还可以给出一些has_many的options,例如得到半年的subscribers:
[code]
class Magazine < ActiveRecord::Base
has_many :subscriptions
has_many :readers, :through => :subscriptions
has_many :semiannual_subscribers,
:through => :subscriptions,
:class_name => "Reader",
:conditions => ['length_in_issues = 6']
end
[/code]
这样我们可以通过magazine.semiannual_subscribers来得到半年的subscribers
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值