Forum: Ruby on Rails Help with nested HABTM relationship

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.
Siros (Guest)
on 2006-01-19 18:41
Hi,

I am trying to perform a query with ActiveRecord that I want to put into
a Rails application later. For now I just wrote it within a plain old
Ruby script for easier testing.

I am working with an existing database so I had to map some foreign keys
myself. As you can see from the models below, the database has a
structure of
Prospectlists <=habtm=> Contacts <=habtm=> Accounts

I want to produce a list of all contacts belonging on a certain prospect
list with their account name.

If I have find one specific contact (ll.28-32), the company name prints.
But if I do the exact same for a number of contacts already selected
from the mailing list (ll.36-41), no company names are printed. No error
is produced.

What am I doing wrong?

     1  # set up the structures
     2  class Prospect_list < ActiveRecord::Base
     3    has_and_belongs_to_many :contacts,
     4      :join_table => "prospect_lists_prospects",
     5      :foreign_key => "prospect_list_id",
     6      :association_foreign_key => "related_id"
     7  end
     8
     9  class Account < ActiveRecord::Base
    10    has_and_belongs_to_many :contacts,
    11    :join_table => "accounts_contacts",
    12    :foreign_key => "account_id",
    13    :association_foreign_key => "contact_id"
    14  end
    15
    16
    17  class Contact < ActiveRecord::Base
    18    has_and_belongs_to_many :prospect_lists,
    19    :join_table => "prospect_lists_prospects",
    20    :foreign_key => "related_id",
    21    :association_foreign_key => "prospect_list_id"
    22    has_and_belongs_to_many :accounts,
    23    :join_table => "accounts_contacts",
    24    :foreign_key => "contact_id",
    25    :association_foreign_key => "account_id"
    26  end
    27
    28  me = Contact.find_by_first_name("Siros")
    29  print me.last_name
    30  me.accounts.each do |company|
    31    puts company.name
    32  end
    33  # => "JohnsonIBM"
    34
    35
    36  mailing = Prospect_list.find_by_name("Hot Leads")
    37  mailing.contacts.each do |person|
    38    puts person.first_name + ' ' + person.last_name
    39  # line below prints nothing
    40    person.accounts.first {|company| puts company.name }
    41  end
    42  # => "Johnson\nFerret\nMüller\n" etc.
This topic is locked and can not be replied to.