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

时间:2014-08-05 22:19:26

标签: 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

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

**编辑**

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

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

问题:

  1. 为什么更改Entity属性会导致更改Location模型?
  2. 为什么效果为DELETE / INSERT,而不是UPDATE

1 个答案:

答案 0 :(得分:3)

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

class Entity < ActiveRecord::Base
  ...
  accepts_nested_attributes_for :location, update_only: true

来源: