Forum: Ruby on Rails newbie question: Trouble getting HABTM to return joined data

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
esloane (Guest)
on 2005-12-02 01:12
(Received via mailing list)
I'm having a stupid moment!
two tables Jobs and Addresses are joined with jobs_addresses.
jobs_addresses has Job_id and Address_id.
In console I can query @job.addresses and see the attribute address_id
but I can't figure out how to populate an address array (or hash) from
that attribute. BTW, the purpose here is to return a list containing job
data with address details attached
Many Thanks,
jamie (Guest)
on 2005-12-02 02:09
(Received via mailing list)
Not quite clear what you want here, but maybe this will help you

First,  has_and_belongs_to_many looks for the joined table names in
alphabetical order. Yours are reversed, so make sure you map them:

has_and_belongs_to_many :addresses, :join_table => "jobs_addresses"

Second, remember you are dealing with a collection, so to deal with
each item you can call each and pass a block, or use find() to get
the specific item:

job.addresses.each do |address|
   #do something to address

address = job.addesses.find(<id>)
#do something to the address

esloane (Guest)
on 2005-12-02 03:06
(Received via mailing list)
Jamie Orchard-Hays wrote:
>> _______________________________________________
>> Rails mailing list
>> removed_email_address@domain.invalid

Hi Jamie - thanks for the response.

What I want to get is a list of jobs containing job_number, job_type,
etc. from Jobs. Appended to each of those I want address_1, address_2,
suburb, etc. from Addresses.

I have the models set to specify the join_table so that's OK (I found
the lexical rating thing yesterday)

When I query @job.addresses in console I see an address_id equal to 2
which is correct. When I try to get that to return an actual address I
run into problems - NoMethodError, etc.. So, I guess I'm asking How do I
get to the address table with this information so eadch job will display
an address in the list.

Thanks again for helping - I guess this is a fundamentally dumb
question, but I'm new to both Ruby and Rails and need some help in
understanding the relationships
This topic is locked and can not be replied to.