Rails 谨慎使用 has_one 带来的 build_association API

hjiangwen · 2020年10月29日 · 270 次阅读

当我们使用 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
暂无回复。
需要 登录 后方可回复, 如果你还没有账号请 注册新账号