What's New in Edge Rails: Has One :through

Posted by ryan
at 11:59 AM on Monday, March 24, 2008



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

Comments

Leave a response

  1. MicahMarch 24, 2008 @ 04:14 PM

    @ryan.magazine.hide_under_matress

  2. BrennanMarch 24, 2008 @ 09:48 PM

    But, uhh.. you’d have many magazines in that case, one for each subscription.

    @ryan.subscriptions.collect(&:magazine)

  3. RyanMarch 25, 2008 @ 09:40 AM

    Brennan:

    has_one will return the first item if the :through association has more than one item. However, in our case, the :conditions on the has_one of only getting the active one will return a single item – so we’re good either way.