Deleting an item from a polymorphic association

Hi,
I am learning RoR and in the process of implmenting a solution I have
run into a problem.

My basic setup:

each customer and sales order could have more than one address, say
‘billing’, ‘shipping’ and may be more.

create_table “addresses”, :force => true do |t|
t.column “address_kind”, :string, :limit => 60
t.column “addressable_id”, :integer, :default => 0
t.column “addressable_type”, :string, :limit => 120

end

create_table “customers”, :force => true do |t|
t.column “company_name”, :string, :limit => 200

end

create_table “sales_orders”, :force => true do |t|
t.column “customer_id”, :integer, :default => 0, :null => false

end

class Address < ActiveRecord::Base
belongs_to :addressable, :polymorphic => true

end

class Customer < ActiveRecord::Base
has_many :addresses, :as => :addressable

has_many :addresses, :as => :addressable, :before_remove =>

:clean_up_address

def billing_address
addresses.find_by_address_kind ‘billing’ unless addresses.empty?
end

def shipping_address
addresses.find_by_address_kind ‘shipping’ unless addresses.empty?
end

def billing_address=(address)
addresses.delete(billing_address) if billing_address
address.address_kind = ‘billing’
addresses << address
end

def shipping_address=(address)
addresses.delete(shipping_address) if shipping_address
address.address_kind = ‘shipping’
addresses << address
end

def clean_up_address(address)
write_attribute(:address_kind, nil)
write_attribute(:addressable_type, nil)
# address.address_kind = nil
# address.addressable_type = nil
end
end

class SalesOrder < ActiveRecord::Base
has_many :addresses, :as => :addressable
… (address related methods similar to customer)
end

I am running into a problem while reassigning, say, a new billing
address to a customer. The addresses.delete(billing_address) in the
billing_address= method updates only the addressable_id to NULL in the
database. I tried to add :before_remove option to the has_many and
implemented the clean_up method. Even then, only the addressable_id is
updated to NULL and not address_kind or addressable_type.

Is this correct approach? And if not, what is the correct approach to
follow while reassigning a new address either to a customer or sales
order?

Your assistance is greatly appreciated.

Thanks

suresh

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