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

问题描述 投票:0回答:2

我有两个具有

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
模型的
url
Entity
属性将导致关联的
Location
记录被删除然后插入。这是一个不太理想的行为。

** 编辑 **

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

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

问题:

  1. 为什么
    Entity
    属性的更改会导致
    Location
    模型的更改?
  2. 为什么这是执行
    DELETE
    /
    INSERT
    ,而不是
    UPDATE
ruby-on-rails ruby-on-rails-4
2个回答
5
投票

解决方案:将

update_only: true
添加到
accepts_nested_attributes_for

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

来源:


0
投票
entity.update(location_attributes: { id: entity.location.id, ... })
© www.soinside.com 2019 - 2024. All rights reserved.