views:

38

answers:

2

This is a method that used to be in the controller and I think it makes more sense to make it a method to the Contact model:

  def colleagues 

    company = Company.find(self.company_id) 

    contacts = company.contacts.collect(&:full_name)

    contacts.each do |contact|
       colleagues = contacts.reject{ |c| c==contact }
    end 

    return colleagues

  end

Each Contact belongs to a Company. Each Company may have many other Contacts. The colleagues of a specific contact are the other members of the Company to which the specified contact belongs to.

I seem to be getting an error, a stack to deep error.

+1  A: 

Is this what you are looking for?

class Contact
  belongs_to :company

  def colleagues
    self.company.contacts
  end
end

If you don't want yourself included in the list of contacts, you can use reject:

class Contact
  belongs_to :company

  def colleagues
    self.company.contacts.reject { |contact| contact == self }
  end
end

Update for your last comment:

def colleagues
  self.company.contacts.collect { |contact| contact.full_name }.to_sentence
end

Or again, if you don't want to include yourself:

def colleagues
  colleagues = self.company.contacts.reject { |contact| contact == self }
  colleagues.collect { |contact| contact.full_name }.to_sentence
end
captaintokyo
how can I make colleagues behave like to_sentence. The usage would be to substitute colleagues so that it outputs like "Contact1, contact2, and Contact3"
Angela
oh, and I display the .full_name for each contact that is a member of colleagues....
Angela
A: 

Try this:

class Contact
  belongs_to :company
  has_many :colleagues, :through => :company, :source  => :contacts, 
                        :conditions => 'contacts.id != #{id}'
end


class Company
  has_many :contacts
end

Now, you can make following calls:

contact.colleagues                              # colleagues list
contact.colleagues.map(&:full_name).to_sentence # colleague names string

You can further optimize the result as follows:

contact.colleagues.all(:select => :full_name).map(&:full_name).to_sentence
KandadaBoggu
This is nice! Unfortunately as output she wants a string not a collection of contacts... Is there a way to use has_many :through and return a string?
captaintokyo
I have updated the answer. Take a look.
KandadaBoggu