destroy_all and delete_all
Destroy the records by instantiating each record and calling its #destroy method.在删除前实例化每条记录,并回调callback execution.
⚠️ :如果想要快速删除,如果这个动作不涉及associations or callbacks, use delete_all instead. 因为delete_all直接使用SQL DELETE .
豆知识:
Transaction: the process of doing business.
在iterm中输入alias,可以显示所有设置的别名:例子ll的别名是“ls -lh”显示详细的文件内容
语言学习法:
1. 用身体记忆(肌肉记忆,第一步是反复做,而不是试图理解背后的逻辑。学习语言包括配合肢体动作)
2. 跟读。(模仿,纠正)
3. 实际环境中使用。(编程就是直接开发项目,边开发边学。语言就是用,说起来。)
4. 不要被语言本身所限制,语言的目的是沟通,只要符合沟通的目的,可以灵活使用。
Active Record Callbacks:简单学一下:
Callbacks are hooks into the life cycle of an Active Record object that allow you to trigger logic before or after an alteration of the object state.
总共有19种回叫。 如 before_validation, before_create, before_destroy.
继续看api文档:http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html
callback可以使用类的继承关系, 当子类的一个before_destroy发生时,也会调用父类的before_destroy.
callback有四种method的写法:symbol, callbackobject, inline method(using a process),还有一种不推荐的忽略。
The method reference callbacks work by specifying a protected or private method available in the object, like this(:symbol):
class Topic < ActiveRecord::Base
before_destroy :delete_parents
private
def delete_parents
self.class.delete_all "parent_id = #{id}"
end
end
callback-object:
before_save EncryptionWrapper.new
after_save EncryptionWrapper.new
Ordering callbacks:
有时候,代码在callbacks执行中需要有特别的顺序。否则会报告❌; 需要使用prepend: true
因为关联的关系的回调和删除是首先执行的,之后才会执行before_destroy.
class Topic < ActiveRecord::Base
has_many :children, dependent: :destroy
before_destroy :log_children, prepend: true
private
def log_children
# Child processing
end
end
Also,there are cases when you want several callbacks of the same type to be executed in order.
如果回调的类型一样,按照代码行顺序执行 .
特例: after_commit,是反过来,先执行最后的method.
http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html 文档包括如何debugging callbacks.