Problems with updating multiple HABTM relationships

have the following models
class Address < ActiveRecord::Base
has_and_belongs_to_many :address_types, :join_table =>
“address_types_addresses”, :foreign_key => “address_id”
has_and_belongs_to_many :organisations

class AddressType < ActiveRecord::Base
has_and_belongs_to_many :addresses, :join_table =>
“address_types_addresses”, :foreign_key => “address_types_id”

class Organisation < ActiveRecord::Base
has_and_belongs_to_many :addresses

An organisation can have a number of different addresses (main,
dispatch, invoice etc). And one address can belong to more than one
organisation (to allow for different companies operating out of the
same address), and an address can be more than one type of address (ie
the invoice address could be the same as the dispatch address, but
different to the main office address).

There are the appropriate join tables: address_types_addresses, and
addresses_organisations.

I have a form that allows a user to add a new address (uses Ryan
Bates’ “Handle Multiple Models in One Form” technique from the
Advanced Rails Recipes book.

Here is the relevant part of the Organisations model:
after_update :save_addresses

def new_address_attributes=(address_attributes)
#handles the address edit form in the edit view
address_attributes.each do |attributes|
addresses.build(attributes)
end
end

def existing_address_attributes=(address_attributes)
addresses.reject(&:new_record?).each do |address|
attributes = address_attributes[address.id.to_s]
if attributes
address.attributes = attributes
else
addresses.delete(address)
end
end
end

def save_addresses
addresses.each do |address|
address.save(false)
end
end

The problem I am having is that the save is great - except for it
doesn’t enter a value in the address_types_address table. Being an
old-fashioned PHP programmer, I am slightly struggling to find out how
to make it update that table as well. I am guessing that since there
is no direct relationship between address_types and organisations,
rails doesn’t know about it. How to tell it … Is this something
simple, or is there a bus-sized hole in the logic?

Any help would be v gratefully received.
Thanks
Ben

Hi BenR

“address_types_addresses”, :foreign_key => “address_types_id”

  Is this address_types_id  Or  address_type_id   ?

Sijo

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs