It would appear that has_one has finally grown up the stature of has_many and now has support for the :through option.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
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 |
The intermediate associations are properly handled when doing assignments as well:
1 2 3 |
@ryan.subscriptions #=> [] @ryan.magazine = Magazine.create(:name => 'Hustler') @ryan.subscriptions #=> [<Subscription magazine_id: 1, user_id: 1 ...>] |
tags: ruby, rubyonrails

@ryan.magazine.hide_under_matress
But, uhh.. you’d have many magazines in that case, one for each subscription.
@ryan.subscriptions.collect(&:magazine)
Brennan:
has_onewill return the first item if the:throughassociation has more than one item. However, in our case, the:conditionson thehas_oneof only getting the active one will return a single item – so we’re good either way.