I have an Address model and an Order model in my Rails app. An order has a billing address and a delivery address. I’m trying to figure out the most efficient way of implementing this with a polymorphic association (other models will also have addresses in future) and this is the code I’ve come up with:
address.rb:
class Address < ActiveRecord::Base
attr_accessible :line_1, :line_2, :city, :county, :postcode
# Also has an 'address_type' attribute
belongs_to :addressable, polymorphic: true
end
order.rb:
class Order < ActiveRecord::Base
has_many :addresses, as: :addressable
def delivery_address
addresses.where(address_type: 'delivery').first
end
def delivery_address=(address)
address.address_type = 'delivery'
addresses << address
end
def billing_address
addresses.where(address_type: 'billing').first
end
def billing_address=(address)
address.address_type = 'billing'
addresses << address
end
end
Adding an address:
Order.first.address = Address.new(line_1: 'My House', city: 'Cityville, county: 'Hazzard')
This almost works except that trying to change an address by calling order.delivery_address= again just adds another address of type ‘delivery’. I’m also pretty sure that there must be a more elegant way of doing it and I’d really appreciate any advice.
1 Answer