谁能告诉我在处理父键被销毁的对象时,这两种方式有什么不同?是什么实际原因让你选择了其中一个?
发布于 2018-01-03 18:29:18
restrict_with_exception
如果有任何关联的记录,则会引发异常,并显示:
class Student< ActiveRecord::Base
has_many :courses, dependent: :restrict_with_exception
has_many :books
endrestrict_with_error
如果存在任何关联的记录,则会向所有者(您尝试删除的记录)添加一个错误,并显示以下信息:
class Foo < ActiveRecord::Base
has_many :bars, dependent: :restrict_with_error
end预期行为
对于标准验证,错误消息包含翻译,错误详细信息包含键,如下所示,错误为空:
f1 = Foo.new
f1.save!
#=> ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
f1.errors
#=> #<ActiveModel::Errors:0x007fb666637af8
#=> @base=#<Foo:0x007fb6666ddbb0 id: nil, name: nil>,
#=> @details={:name=>[{:error=>:blank}], :type=>[{:error=>:blank}]},
#=> @messages={:name=>["can't be blank"], :type=>["can't be blank"]}>发布于 2018-01-03 17:15:38
这些都是从属选项
依赖选项是什么?
dependent选项是一个选项,用于在删除父记录时决定在Rails模型有子记录的情况下如何处理子记录。
restrict_with_exception
:restrict_with_exception -如果有任何关联的记录,将引发异常。
:restrict_with_exception -如果有子记录,那么您的ActiveRecord::DeleteRestrictionError将遇到。
restrict_with_error
:restrict_with_error -如果有任何关联的记录,则会向所有者(您试图删除的记录)添加一个错误。
:restrict_with_error -如果存在子记录,则无法将其删除,并将错误信息添加到父记录中。
除了那些之外的几个选项
:destroy -删除包含父项的子项记录。
:delete_all -删除包含父项的子项记录。然而,由于DB的记录被直接删除,所以不执行子记录的回调处理。
:nullify NULL -更新子记录的外键。
你也可以在谷歌上搜索更多
发布于 2021-05-30 00:42:12
出自傻瓜德夫的答案
你也可以在谷歌上搜索更多
不需要这样做。在Active Record源代码中:
def self.valid_dependent_options
[:destroy, :delete_all, :nullify, :restrict_with_error, :restrict_with_exception, :destroy_async]
end所以,这个列表已经差不多完成了,只剩下:destroy_async留给谷歌了。下面是它的功能,来自文档:
如果设置为
:destroy_async,则计划在后台作业中销毁关联的对象。
https://stackoverflow.com/questions/48071054
复制相似问题