作者:Ryan Daigle 来源:JavaEye 酷勤网收集 2008-05-29
摘要
rails2.1中新特性的文章.这里是这个系列中的一篇. Has one :through,has_one终于长得和has_many一样高了,它也支持了:through选项. 并且当through属性改变后,中间属性会随之改变.当through连接有多个record,has_one会返回第一个.
系列文章汇总《Ruby on Rails 2.1新特性》
Ryan Daigle发布了一系列关于rails2.1中新特性的文章.这里是这个系列中的一篇.
Has one :through
has_one终于长得和has_many一样高了,它也支持了:through选项.
- class Magazine < ActiveRecord::Base
- has_many :subscriptions
- end
- class Subscription < ActiveRecord::Base
- belongs_to :magazine
- belongs_to :user
- end
- class User < ActiveRecord::Base
- has_many :subscriptions
- has_one :magazine, :through => : subscriptions, :conditions => ['subscriptions.active = ?', true]
- end
class Magazine < ActiveRecord::Base has_many :subscriptions end class Subscription < ActiveRecord::Base belongs_to :magazine belongs_to :user end class User < ActiveRecord::Base has_many :subscriptions has_one :magazine, :through => : subscriptions, :conditions => ['subscriptions.active = ?', true] end
并且当through属性改变后,中间属性会随之改变
- @ryan.subscriptions #=> []
- @ryan.magazine = Magazine.create(:name => 'Hustler')
- @ryan.subscriptions #=> [<Subscription magazine_id: 1, user_id: 1 ...>]
@ryan.subscriptions #=> [] @ryan.magazine = Magazine.create(:name => 'Hustler') @ryan.subscriptions #=> [<Subscription magazine_id: 1, user_id: 1 ...>]
译者注: 当through连接有多个record,has_one会返回第一个.
原文:http://ryandaigle.com/
来自:http://www.javaeye.com/news/2320


