Reputation: 7832
There are two models:
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
objectTGroup.first.favorite
# will return the favorite T object of the TGroup.first
objectTGroup.first.ts << T.first
# will attach T.first object to the TGroup.first
objectTGroup.first.favorite = T.first
# will set the T.first
object as the
favorite of TGroup.first
objectThe solution I tried to implement was:
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.
Upvotes: 0
Views: 70
Reputation: 2923
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.
Upvotes: 2