Q:

has_many and has_one associations

There are two models:

T
TGroup

TGroup object may have many T objects.
TGroup object has one favorite T object.
I want to define associations that will provide me the following functionality:

TGroup.first.ts # will return list of T objects belong to TGroup.first object
TGroup.first.favorite # will return the favorite T object of the TGroup.first object
TGroup.first.ts << T.first # will attach T.first object to the TGroup.first object
TGroup.first.favorite = T.first # will set the T.first object as the
favorite of TGroup.first object

The solution I tried to implement was:

Define t_group_id field (integer) on T
Define favorite_id field (integer) on TGroup
Define the following associations on TGroup model

has_many :ts, :class_name => T.to_s
has_one :t, :class_name => T.to_s, :foreign_key => :id, :primary_key => :favorite_id

I didn't succeed to define the "favorite" (should be something like ":as => :favorite"?) alias so I started with "t" instead.
Unfortunately, doing that I can't set TGroup.first.t = T.first. Instead of setting the TGroup.first.t.id to T.first.id it makes changes on T model.

A:

I think that what you need is a belongs_to association rather than a has_one one.
According to the docs the foreign key goes on the table for the class declaring the belongs_to association, so something like this should do the job:
belongs_to :favorite, :class_name => T.to_s

The has_one/belongs_to associations can be sometimes a bit confusing depending on each particular context.
Hope this helps.

