将 Rails has_one 关系修改为 UPDATE 而不是 DELETE 然后 INSERT

cra*_*aig 3 ruby-on-rails ruby-on-rails-4

我有两个模型有has_one关系:

class Entity < ActiveRecord::Base

  has_one :location, as: :locatable, dependent: :destroy
  accepts_nested_attributes_for :location, allow_destroy: true

  ...
  default_scope {joins(:location).includes(:location)}
  ...

  # has a properties 'name' and 'url'

end

class Location < ActiveRecord::Base
  belongs_to :locatable, polymorphic: true

  # has a property named 'address'

end
Run Code Online (Sandbox Code Playgroud)

我注意到通过表单更改模型的name或url属性Entity将导致关联的Location记录被删除然后插入。这是一个不太理想的行动。

** 编辑 **

在进一步的测试中,我注意到这些设置与 SQL 策略无关:

  • polymorphic 加入
  • allow_destroy: true
  • dependent: :destroy- 除了在Locations表中留下孤立记录
  • default_scope

问题:

  1. 为什么对Entity属性的更改会导致对Location模型的更改?
  2. 为什么这是执行DELETE/ INSERT,而不是UPDATE?

cra*_*aig 5

解决方案:添加update_only: true到accepts_nested_attributes_for:

class Entity < ActiveRecord::Base
  ...
  accepts_nested_attributes_for :location, update_only: true
Run Code Online (Sandbox Code Playgroud)

资料来源: