Rails 奇怪的现象,正常的 new 和 save,什么情况会导致数据没有保存完整?

QueXuQ · May 09, 2015 · Last by chenge replied at May 09, 2015 · 1262 hits

我有一个 Product 和 Order,Storehouse,Product belongs_to Order,Order belongs_to Storehouse 然后创建的操作是这样的:

order = Order.find(params[:order_id])
product = Product.new
product.name = 'xxx'
product.number = 'xxx'
product.order_number = order.storehouse.name
product.save

虽然逻辑很简单,但是我偶尔去查数据库,发现 product order_number 会出现为空的情况。可是都是同一个 order 的情况,会出现有为空,有不为空。 请问导致这种现象会是什么原因呢?我只能想到可能 order_id 没传过去,可是如果 order id 没有,那也不可能 save 的了呢。

会不会是这个情况?

c = Customer.first
o = c.orders.first
c.first_name == o.customer.first_name # => true
c.first_name = 'Manny'
c.first_name == o.customer.first_name # => false

可参考文档

storehouse.name 检查下,很可能是这个吧。

You need to Sign in before reply, if you don't have an account, please Sign up first.