我有两个具有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
模型的name
或url
属性的更改将导致相关的Location
记录被删除,然后被删除。这是一个不太理想的操作。
编辑
在进一步的测试中,我注意到这些设置对SQL策略没有影响:
polymorphic
加入allow_destroy: true
个dependent: :destroy
-除了在Locations
表中留下孤立记录之外default_scope
个
问题:
1.为什么对Entity
属性的更改会导致对Location
模型的更改?
1.为什么执行DELETE
/INSERT
,而不是UPDATE
?
2条答案
按热度按时间ssm49v7z1#
解决方案:将
update_only: true
添加到accepts_nested_attributes_for
:字符串
资料来源:
accepts_nested_attributes_for(*attr_names)
的API文档ufj5ltwl2#
在嵌套属性中添加id将执行
UPDATE
,而不是DELETE/INSERT
。字符串