I have following model:
class Customer < ActiveRecord::Base
has_one :cart
end
class Cart < ActiveRecord::Base
belongs_to :customer
validates :customer, :presence => true
end
In following case, Cart object is invalid and not saved to DB:
c = Cart.create
c.valid? # false
In following case, Cart object is valid and saved to DB:
c = Cart.create
cus = Customer.create
c.customer = cus
c.valid? # true
In following, third case, Cart object is also valid and saved to the DB:
cus = Customer.create
cus.cart = Cart.create
The question is – why the last case produces valid Cart record, that will be saved ?
When following stack-like code evaluation schema, Cart.create is eveluated before being passed to Customer.cart= method. Therefore, association of Cart with Customer is not established at this moment, and, theoretically, should produce invalid Cart that should not be saved to DB.
Why saving of Cart happens ?
I guess, cart object is marked as “to-be-saved”, when it was created with create method and is invalid. When passed to Customer.cart= method, cart is associated with customer and Cart.save will be called, when cart is marked as “to-be-saved”. So, we get cart model, saved to DB.
Am I right ?
…/activerecord-3.0.8/lib/active_record/base.rb:476 (create method)
also …/activerecord-3.0.8/lib/active_record/associations.rb:1003 (has_one method)