有人能告诉我,处理父键被销毁的对象时,这两种方式有什么区别?在实践中,是什么原因使你选择其中一种而不是另一种?
有人能告诉我,处理父键被销毁的对象时,这两种方式有什么区别?在实践中,是什么原因使你选择其中一种而不是另一种?
restrict_with_exception
如果有任何关联记录,将会抛出一个异常:
class Student< ActiveRecord::Base
has_many :courses, dependent: :restrict_with_exception
has_many :books
end
restrict_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"]}>
这些是依赖选项
什么是依赖选项?
当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
- 更新子记录的外键。
您也可以搜索更多内容。
来自fool-dev的回答
你也可以谷歌搜索更多内容
不需要这样做。来自ActiveRecord
源代码:
def self.valid_dependent_options
[:destroy, :delete_all, :nullify, :restrict_with_error, :restrict_with_exception, :destroy_async]
end
:destroy_async
需要谷歌一下。以下是它的作用,来自文档::destroy_async
,关联对象将被安排在后台作业中销毁。