Rails 谨慎使用 has_one 带来的 build_association API

hjiangwen · October 29, 2020 · 268 hits

当我们使用 build_association 时,即使新的 model 对象还没有保存,旧的 association 就已经取消关联了(外键被置空/直接删除)

class Address
  belongs_to :customer
end

class Customer
  has_one :address
end

c = Customer.create!
address1 = Address.create!(customer: c)
address2 = c.build_address # 还没插入 address2 到数据库
puts address1.reload.customer_id # => nil
No Reply at the moment.
You need to Sign in before reply, if you don't have an account, please Sign up first.