Reputation: 16724
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.
Upvotes: 0
Views: 78
Reputation: 64363
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
Upvotes: 0
Reputation: 43298
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
Upvotes: 2