Forum: Ruby on Rails Multiple Associations With The Same Object

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.
Fc9250fe89fd5c9e8cfb19c1469a3f86?d=identicon&s=25 Stephen Gerstacker (Guest)
on 2006-01-05 00:03
I have a Company object which has multiple Contacts
(has_many/belongs_to)  I would like one of the contacts to be the
primary contact.  What's the best way to do this?  Right now I have:

create table companies (
 id int not null auto_increment,
 name varchar(50) not null,
 primary_id int null,
 constraint fk_company_primary_contact foreign key (primary_id)
references contacts(id),
 primary key (id)
);

create table contacts (
 id int not null auto_increment,
 name varchar(100) not null,
 company_id int not null,
 primary key (id)
);

class Company < ActiveRecord::Base

  has_many :contacts
  has_one :primary_contact,
          :class_name => 'Contact'

  ...
end

class

class Contact < ActiveRecord::Base

  belongs_to :company

  ...
end

Can someone help me?
4cacb94a089bfbf0541db7b9c8081f74?d=identicon&s=25 Kevin Bedell (Guest)
on 2006-01-05 00:20
(Received via mailing list)
I've not tried it, but I'd think you could do something like this:


class Company < ActiveRecord::Base
  has_many :contacts
  has_one :primary_contact
  ...
end


class Contact < ActiveRecord::Base
  belongs_to :company
  ...
end

class PrimaryContact < Contact
end


Although you may have to add a "where clause" to the PrimaryContact
class to
define how to identify the primary contact.
This topic is locked and can not be replied to.