In my app, the main objects are Accounts and Phones, with a typical has_many :through Contacts, eg:
Account:
has_many :contacts
has_many :phones, :though => contacts
Phone:
has_many :contacts
has_many :accounts, :though => :contacts
Contact:
belongs_to :account
belongs_to :phone
Contacts has fields signup_status, name
There is one Contact per unique Account/Phone pair
For an account with id = 123, which has 5 contacts, each contact having one phone, is there a query that would yield all 5 rows and include all the account fields AND contact fields AND phone fields?
You can use eager loading of associations to get all the data you need in one active record query
, which will actually translate into three SQL queries:
All of the records will be loaded into memory and become available through @account. To get the array of contacts and phones, just call
@account.contactsand@account.phones, respectively. Note that these calls will not result in re-issued SQL queries, which is the beauty of eager loading.