Forum: Ruby on Rails has_one behavior - AWDWR page 332

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
B7a15848864437bab1ce7f240b536c66?d=identicon&s=25 Karthik Nar (pearl8)
on 2007-01-23 20:44
(Received via mailing list)
Hi,

On AWDWR page 332 there is this example

class Order < ActiveRecord::Base
  has_one :invoice
end

order = Order.new(... attributes ...)
invoice = Invoice.new(... attributes ...)
order.invoice = invoice

And then the explanation:  If there is already an existing child object
when you assign a new object to a has_one association, that existing
object will be updated to remove its foreign key association with the
parent row(the foreign key will be set to null)

I find that however that if:

1) I change has_one :invoice :dependent => :destroy then the existing
object is actually DELETED rather than just FK being set to null

2) However for the same has_one :invoice :dependent => :destroy if I
use build_invoice instead of assignment
i.e. order.build_invoice instead of order.invoice = invoice
then the Existing object's FK is NULLED out and NOT deleted.

I'm just trying to figure if:

a) Both observations above are correct
b) Why the difference in behavior - i.e. assignment DELETEs the
existing record, whereas build_association NULLs the FK
This topic is locked and can not be replied to.