我有以下型号:
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
在下列情况下,Cart对象有效并保存到DB:
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之前得到体现。因此,此时尚未建立Cart与Customer的关联,理论上应该生成不应保存到DB的无效Cart。
为什么要保存购物车?
我想,当使用create方法创建购物车对象时,购物车对象被标记为“待保存”并且无效。传递给Customer.cart =方法时,购物车与客户关联,当购物车标记为“待保存”时,将调用Cart.save。所以,我们得到购物车模型,保存到DB。
我是对的吗?
答案 0 :(得分:0)
... / activerecord-3.0.8 / lib / active_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_record / associations.rb:1003(has_one方法)
# [association=(associate)]
# Assigns the associate object, extracts the primary key, sets it as the foreign key,
# and saves the associate object.
答案 1 :(得分:0)
<…your hypothesis…>
我是对的吗?
是