Forum: Ruby on Rails two has_one's?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
77de07899eecea8c0fa6c6de19d535e5?d=identicon&s=25 siegi (Guest)
on 2007-03-11 21:59
(Received via mailing list)
Hi,

I'd like to associate two model objects such as

class Pair < ActiveRecord::Base
  has_one :good_member, :class_name=>'Member'
  has_one :bad_member, :class_name=>'Member'
end

class Member < ActiveRecord::Base
  belongs_to :pair
end

so that a pair has two members where one is good and the other is bad.

As far as I understand, the association information would be kept in
the "member" database table as a foreign key to the associated "pair"
record, e.g. member_id

Since the association information is not kept within the "pair" table
- where it would be possible to distinguish between the good and the
bad member, how can I do the above association?

It would be quite comfortable to declare this kind of relationship in
the style above.

Many thanks in advance,
Siegi
2f9a03aa0fcfe945229cb6126eda2cb2?d=identicon&s=25 Philip Hallstrom (Guest)
on 2007-03-12 17:27
(Received via mailing list)
>
> so that a pair has two members where one is good and the other is bad.
>
> As far as I understand, the association information would be kept in
> the "member" database table as a foreign key to the associated "pair"
> record, e.g. member_id
>
> Since the association information is not kept within the "pair" table
> - where it would be possible to distinguish between the good and the
> bad member, how can I do the above association?

#
# sql table has columns:
# memberable_type, :string
# memberagble_id, :integer
#
class Member < ActiveRecord::Base
   belongs_to :memberable, :polymorphic => true
end

class GoodMember < Member
end

class BadMember < Member
end

class Pair < ActiveRecord::Base
   has_one :good_member, :as => :memberable
   has_one :bad_member, :as => :memberable
end
This topic is locked and can not be replied to.