Ask A Question

Notifications

You’re not receiving notifications from this thread.

Muliple has_one's on a polymorphic association

John Meehan asked in General

I wish to add a billing_address and a delivery_address to my Client's.
So i thought i would make my Addresses polymorphic.

class Client < ActiveRecord::Base
  has_many :addresses, as: :addressable
  has_one :delivery_address, class_name: 'Address', as: :addressable
  has_one :billing_address, class_name: 'Address', as: :addressable

  def delivery_address
    super || NullAddress.new
  end

  def billing_address
    super || NullAddress.new
  end
end

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

  def full_address
    [line1, line2, town, county, postcode].compact.join(', ')
  end
end

How ever when i try to update the billing address @client.billing_address
both the @client.billing_address and @client.delivery_address get set to the same address. And the previous addresses :addressable_id gets set to nil.

  [1] #<Address:0x007f8bb1acdf20> {
      :addressable_id => nil,
    :addressable_type => "Client",
             :country => "Ireland",
              :county => "Limerick",
          :created_at => Sat, 25 Jun 2016 17:43:48 UTC +00:00,
                  :id => 2,
               :line1 => "123 New Street",
               :line2 => "College Court",
            :postcode => "DTW1234",
                :town => "Limerick",
          :updated_at => Sat, 25 Jun 2016 17:44:46 UTC +00:00
  },
  [2] #<Address:0x007f8bb1ace060> {
      :addressable_id => 25,
    :addressable_type => "Client",
             :country => "Ireland",
              :county => "Limerick",
          :created_at => Sat, 25 Jun 2016 17:44:46 UTC +00:00,
                  :id => 3,
               :line1 => "126 New Street",
               :line2 => "College Court",
            :postcode => "DTW1234",
                :town => "Limerick",
          :updated_at => Sat, 25 Jun 2016 17:58:14 UTC +00:00
  }

]

Obviously I can still see all the addresses doing @client.addresses. But how do I implement and maintain reference to separate billing and delivery address for a client.

Any tips/pointers welcome,
Thanks :)

Reply

Hmm, I wonder if you need to include the address ID in the form as a hidden field so Rails knows which records to update. If it doesn't have the ID of the nested model, it is just going to create a new one, so that might be what's happening here. It seems like it's creating new records instead of updating the old ones. Does that sound right?

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 82,329+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.