ruby-on-rails 将Rails has_one关系修改为UPDATE,而不是将其转换为UPDATE

ivqmmu1c  于 7个月前  发布在  Ruby
关注(0)|答案(2)|浏览(94)

我有两个具有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

字符串
我注意到通过表单对Entity模型的nameurl属性的更改将导致相关的Location记录被删除,然后被删除。这是一个不太理想的操作。

编辑

在进一步的测试中,我注意到这些设置对SQL策略没有影响:

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

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

ssm49v7z

ssm49v7z1#

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

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

字符串
资料来源:

ufj5ltwl

ufj5ltwl2#

在嵌套属性中添加id将执行UPDATE,而不是DELETE/INSERT

entity.update(location_attributes: { id: entity.location.id, ... })

字符串

相关问题