ruby中的调用序列

ruby中的调用序列,ruby,validation,activerecord,evaluation,Ruby,Validation,Activerecord,Evaluation,我有以下型号: class Customer < ActiveRecord::Base has_one :cart end class Cart < ActiveRecord::Base belongs_to :customer validates :customer, :presence => true end 在以下情况下,Cart对象有效并保存到DB: c = Cart.create c.valid? # false c = Cart.create c

我有以下型号:

class Customer < ActiveRecord::Base
  has_one :cart
end

class Cart < ActiveRecord::Base
  belongs_to :customer

  validates :customer, :presence => true
end
在以下情况下,Cart对象有效并保存到DB:

c = Cart.create
c.valid? # false
c = Cart.create
cus = Customer.create
c.customer = cus
c.valid? # true
在以下第三种情况下,Cart对象也有效并保存到DB中:

cus = Customer.create
cus.cart = Cart.create
问题是-为什么最后一个案例会生成有效的购物车记录,并将其保存

当遵循类似堆栈的代码求值模式时,Cart.create在传递给Customer.Cart=method之前进行了开发。因此,此时未建立购物车与客户的关联,理论上,应产生不应保存到DB的无效购物车

为什么要保存购物车

我猜,cart对象在使用create方法创建时被标记为要保存,并且是无效的。当传递给Customer.cart=方法时,cart与Customer关联,当cart标记为要保存时,将调用cart.save。所以,我们得到了购物车模型,保存到数据库中


我说得对吗?

../activerecord-3.0.8/lib/active\u record/base.rb:476创建方法

# Creates an object (or multiple objects) and saves it to the database, if validations pass.
# The resulting object is returned whether the object was saved successfully to the database or not.
另外…/activerecord-3.0.8/lib/active\u record/associations.rb:1003有一个方法

# [association=(associate)]
#   Assigns the associate object, extracts the primary key, sets it as the foreign key,
#   and saves the associate object.
我说得对吗