zoukankan      html  css  js  c++  java
  • 12月21日 简单理解Active Recore Callback, destroy_all和delete_all的区别。豆知识(alias),语言学习法(4核心)

    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.


  • 相关阅读:
    相对定位
    51nod三大经典博弈(模板)
    51nod1306斐波那契公约数(数论推公式,矩阵快速幂优化递推序列)
    洛谷P1313计算系数(数学二项式次方展开定理,快速幂,除法取模逆元)
    hduoj1052田忌赛马(贪心好题略难,思维,模拟)
    洛谷P1134阶乘问题(数论,末尾0的个数变形,思维转换)
    洛谷P又是毕业季2(数学数论,找规律,公约数)
    洛谷p1309瑞士轮(好题,理解归并排序本质)
    洛谷p1582倒水(思维好题,数学,2进制问题,代码实现)
    洛谷p1338末日的传说(思维好题,数学)
  • 原文地址:https://www.cnblogs.com/chentianwei/p/8078523.html
Copyright © 2011-2022 走看看