SlideShare a Scribd company logo
1 of 27
Ror lab. season 2
      - the 7th round -


      Active Record
Callbacks & Observers

       October 6th, 2012

        Hyoseong Choi
Contents
      Validations                         Callbacks
•   The Object Life Cycle          •   Callbacks Overview
•   Validations Overview           •   Available Callbacks
•   Validation Helpers             •   Running Callbacks
•   Common Validation              •   Skipping Callbacks
    Options                        •   Halting Execution
•   Conditional Validation         •   Relational Callbacks
•   Custom Validations             •   Conditional Callbacks
•   Working with Validation        •   Callback Classes
    Errors
                                   •   Observers
•   Displaying Validation Errors
                                   •   Transaction Callbacks
    in the View
Life-cycle of
   Objects
                DB
Life-cycle of
   Objects
                  DB
    Active
    Record




             el
        od
      M
Life-cycle of
Active
Record
         el      Objects
    od
  M




                              DB
         Create    Save

              Object

         Delete   Update
Life-cycle of
Active
Record
         el      Objects
    od
  M




                                              DB
         Create    Save




                                 Validation
              Object

         Delete   Update

                          load
Callbacks
• Methods : protected or private
• Before or after certain moments of an
  object’s life cycle
• 6create, save, update, delete, validate, load
  :
    events

• Register using a macro-style class method
  ★ as an ordinary method or
  ★ supply as a block
Available Callbacks
★ Creating an Object          ★ Updating an Object     ★ Destroying an Object
•   before_validation         •   before_validation    • before_destroy
•   after_validation          •   after_validation     • around_destroy
•   before_save               •   before_save          • after_destroy
•   before_create             •   before_update
•   around_create             •   around_update
•   after_create              •   after_update
•   after_save                •   after_save



                                                      DB
                 Validation




                                         Create
                                  Save
                                         Update

                                     Destroy
After_find
 > After_initialize
class User < ActiveRecord::Base
  after_initialize do |user|
    puts "You have initialized an object!"
  end
 
  after_find do |user|
    puts "You have found an object!"
  end
end
 
>> User.new
You have initialized an object!
=> #<User id: nil>
 
>> User.first
You have found an object!
You have initialized an object!
=> #<User id: 1>
Methods
Triggering Callbacks
•
•
    create
    create!
                              ‘after_find’ callback
•   decrement!                •   all
•   destroy                   •   first
•   destroy_all               •   find
•   increment!                •   find_all_by_attribute
•   save                      •   find_by_attribute
•   save!
                              •   find_by_attribute!
•   save(:validate =>false)
•   toggle!                   •   last
•   update
•   update_attribute
•   update_attributes
•   update_attributes!
•   valid?
Methods
 Skipping Callbacks
• decrement
• decrement_counter
• delete
• delete_all
• find_by_sql
• increment
• increment_counter
• toggle
• touch
• update_column
• update_all
• update_counters
Methods Calling Callbacks       Methods Skipping Callbacks

create

create!

decrement!                          decrement / ~_counter

destroy                             delete

destroy_all                         delete_all

increment!                          increment / ~_counter

save

save!

save(false)

toggle!                             toggle

update

update_attribute                    update_column

update_attributes                   update_all

update_attributes!                  update_counters

valid?

                                    find_by_sql

                                    touch
Halting Execution
• Queue
    ★ validations for model
    ★ registered callbacks
    ★ database operations
•   Wrapped in a Transaction
    ★ before_ callbacks
      : false or exception > stopped > ROLLBACK
    ★ after_ callbacks
      : exception > stopped > ROLLBACK
Relational
Callbacks
Conditional
         Callbacks

• As with validations
  ★ Using :if and :unless with a Symbol
  ★ Using :if and :unless with a String
  ★ Using :if and :unless with a Proc
Conditional
             Callbacks
                                   as a symbol




                                    as a string




                       as a Proc


* multiple conditions possible!
Callback Classes
  • To reuse callback methods for other models
      as an instance method
                          a model object


instance
method
Callback Classes
as a class method
Observers
• Similar to callbacks
• for the callbacks with the code that isn’t
  directly related the model
• without changing the code of the model
• ex. sending confirmation email after user
  registration
Creating Observers
Registering Observers
 • config/application.rb
 • or config/environments
Sharing Observers
  as a model name
Transaction
       Callbacks
• after_commit or after_rollback
감사합니다.
 
Macro-style class methods :

             As Ordinary
              Methods
     class User  ActiveRecord::Base
       validates :login, :email, :presence = true
      
       before_validation :ensure_login_has_a_value
      
       protected
       def ensure_login_has_a_value
         if login.nil?
           self.login = email unless email.blank?
         end
       end
public/protected/private
                    parent
                                                          pr
                     class                                  iv
                                                                 at                child
                                                                    e_
                                                                      m
               private


                                                                       et
                                                                          ho
                                                                                   class
                         protected
      public                                                                d

                                                                         private
                              (sel
                                   f.)p




                                                                                   protected
                                       rote




                                                         public
                                       ed_ ct
                                           met
                                               hod




http://stackoverflow.com/questions/4495078/protected-and-private-methods-in-rails

More Related Content

What's hot

Découverte de Elastic search
Découverte de Elastic searchDécouverte de Elastic search
Découverte de Elastic searchJEMLI Fathi
 
webservice scaling for newbie
webservice scaling for newbiewebservice scaling for newbie
webservice scaling for newbieDaeMyung Kang
 
Mongo DB 성능최적화 전략
Mongo DB 성능최적화 전략Mongo DB 성능최적화 전략
Mongo DB 성능최적화 전략Jin wook
 
Rust Programming Language
Rust Programming LanguageRust Programming Language
Rust Programming LanguageJaeju Kim
 
게임서비스를 위한 ElastiCache 활용 전략 :: 구승모 솔루션즈 아키텍트 :: Gaming on AWS 2016
게임서비스를 위한 ElastiCache 활용 전략 :: 구승모 솔루션즈 아키텍트 :: Gaming on AWS 2016게임서비스를 위한 ElastiCache 활용 전략 :: 구승모 솔루션즈 아키텍트 :: Gaming on AWS 2016
게임서비스를 위한 ElastiCache 활용 전략 :: 구승모 솔루션즈 아키텍트 :: Gaming on AWS 2016Amazon Web Services Korea
 
Memory Corruption: from sandbox to SMM
Memory Corruption: from sandbox to SMMMemory Corruption: from sandbox to SMM
Memory Corruption: from sandbox to SMMPositive Hack Days
 
從狗熊到英雄 - 我的.Net 6 blazor新體驗
從狗熊到英雄 - 我的.Net 6 blazor新體驗從狗熊到英雄 - 我的.Net 6 blazor新體驗
從狗熊到英雄 - 我的.Net 6 blazor新體驗Ron Zhong
 
Rapid JCR applications development with Sling
Rapid JCR applications development with SlingRapid JCR applications development with Sling
Rapid JCR applications development with SlingBertrand Delacretaz
 
Momenti Seminar - A Tour of Rust, Part 2
Momenti Seminar - A Tour of Rust, Part 2Momenti Seminar - A Tour of Rust, Part 2
Momenti Seminar - A Tour of Rust, Part 2Chris Ohk
 
[MLOps KR 행사] MLOps 춘추 전국 시대 정리(210605)
[MLOps KR 행사] MLOps 춘추 전국 시대 정리(210605)[MLOps KR 행사] MLOps 춘추 전국 시대 정리(210605)
[MLOps KR 행사] MLOps 춘추 전국 시대 정리(210605)Seongyun Byeon
 
Introduction NoSQL 201401 - Ensim
Introduction NoSQL 201401 - EnsimIntroduction NoSQL 201401 - Ensim
Introduction NoSQL 201401 - EnsimLaurent Broudoux
 
[2D1]Elasticsearch 성능 최적화
[2D1]Elasticsearch 성능 최적화[2D1]Elasticsearch 성능 최적화
[2D1]Elasticsearch 성능 최적화NAVER D2
 
Advanced Use of jinja2 for Templates
Advanced Use of jinja2 for TemplatesAdvanced Use of jinja2 for Templates
Advanced Use of jinja2 for TemplatesKeith Resar
 
Baffin Winter Boots 2014 Catalog English
Baffin Winter Boots 2014 Catalog EnglishBaffin Winter Boots 2014 Catalog English
Baffin Winter Boots 2014 Catalog EnglishTheToolStore.ca
 
Building a Social Network with MongoDB
Building a Social Network with MongoDBBuilding a Social Network with MongoDB
Building a Social Network with MongoDBLewis Lin 🦊
 
[131]chromium binging 기술을 node.js에 적용해보자
[131]chromium binging 기술을 node.js에 적용해보자[131]chromium binging 기술을 node.js에 적용해보자
[131]chromium binging 기술을 node.js에 적용해보자NAVER D2
 
Cisco 2900 series router, more benefits, high performance
Cisco 2900 series router, more benefits, high performanceCisco 2900 series router, more benefits, high performance
Cisco 2900 series router, more benefits, high performanceIT Tech
 

What's hot (20)

Découverte de Elastic search
Découverte de Elastic searchDécouverte de Elastic search
Découverte de Elastic search
 
webservice scaling for newbie
webservice scaling for newbiewebservice scaling for newbie
webservice scaling for newbie
 
Mongo DB 성능최적화 전략
Mongo DB 성능최적화 전략Mongo DB 성능최적화 전략
Mongo DB 성능최적화 전략
 
Rust Programming Language
Rust Programming LanguageRust Programming Language
Rust Programming Language
 
게임서비스를 위한 ElastiCache 활용 전략 :: 구승모 솔루션즈 아키텍트 :: Gaming on AWS 2016
게임서비스를 위한 ElastiCache 활용 전략 :: 구승모 솔루션즈 아키텍트 :: Gaming on AWS 2016게임서비스를 위한 ElastiCache 활용 전략 :: 구승모 솔루션즈 아키텍트 :: Gaming on AWS 2016
게임서비스를 위한 ElastiCache 활용 전략 :: 구승모 솔루션즈 아키텍트 :: Gaming on AWS 2016
 
Memory Corruption: from sandbox to SMM
Memory Corruption: from sandbox to SMMMemory Corruption: from sandbox to SMM
Memory Corruption: from sandbox to SMM
 
從狗熊到英雄 - 我的.Net 6 blazor新體驗
從狗熊到英雄 - 我的.Net 6 blazor新體驗從狗熊到英雄 - 我的.Net 6 blazor新體驗
從狗熊到英雄 - 我的.Net 6 blazor新體驗
 
Rapid JCR applications development with Sling
Rapid JCR applications development with SlingRapid JCR applications development with Sling
Rapid JCR applications development with Sling
 
Momenti Seminar - A Tour of Rust, Part 2
Momenti Seminar - A Tour of Rust, Part 2Momenti Seminar - A Tour of Rust, Part 2
Momenti Seminar - A Tour of Rust, Part 2
 
[MLOps KR 행사] MLOps 춘추 전국 시대 정리(210605)
[MLOps KR 행사] MLOps 춘추 전국 시대 정리(210605)[MLOps KR 행사] MLOps 춘추 전국 시대 정리(210605)
[MLOps KR 행사] MLOps 춘추 전국 시대 정리(210605)
 
Introduction NoSQL 201401 - Ensim
Introduction NoSQL 201401 - EnsimIntroduction NoSQL 201401 - Ensim
Introduction NoSQL 201401 - Ensim
 
[2D1]Elasticsearch 성능 최적화
[2D1]Elasticsearch 성능 최적화[2D1]Elasticsearch 성능 최적화
[2D1]Elasticsearch 성능 최적화
 
Advanced Use of jinja2 for Templates
Advanced Use of jinja2 for TemplatesAdvanced Use of jinja2 for Templates
Advanced Use of jinja2 for Templates
 
Baffin Winter Boots 2014 Catalog English
Baffin Winter Boots 2014 Catalog EnglishBaffin Winter Boots 2014 Catalog English
Baffin Winter Boots 2014 Catalog English
 
Building a Social Network with MongoDB
Building a Social Network with MongoDBBuilding a Social Network with MongoDB
Building a Social Network with MongoDB
 
[131]chromium binging 기술을 node.js에 적용해보자
[131]chromium binging 기술을 node.js에 적용해보자[131]chromium binging 기술을 node.js에 적용해보자
[131]chromium binging 기술을 node.js에 적용해보자
 
MOPCON_2022.pdf
MOPCON_2022.pdfMOPCON_2022.pdf
MOPCON_2022.pdf
 
شبکه های اجتماعی علمی
شبکه های اجتماعی علمیشبکه های اجتماعی علمی
شبکه های اجتماعی علمی
 
Cisco 2900 series router, more benefits, high performance
Cisco 2900 series router, more benefits, high performanceCisco 2900 series router, more benefits, high performance
Cisco 2900 series router, more benefits, high performance
 
STACK OVERFLOW DATASET ANALYSIS
STACK OVERFLOW DATASET ANALYSISSTACK OVERFLOW DATASET ANALYSIS
STACK OVERFLOW DATASET ANALYSIS
 

Viewers also liked

Beyond Profilers: Tracing Node.js Transactions
Beyond Profilers: Tracing Node.js TransactionsBeyond Profilers: Tracing Node.js Transactions
Beyond Profilers: Tracing Node.js TransactionsTerral R Jordan
 
Getting Started with Rails (4)
Getting Started with Rails (4) Getting Started with Rails (4)
Getting Started with Rails (4) RORLAB
 
Risk management in e banking
Risk management in e bankingRisk management in e banking
Risk management in e bankingAmer Mushtaq
 
Sample Call Center Hierarchy 8.13.07
Sample Call Center Hierarchy 8.13.07Sample Call Center Hierarchy 8.13.07
Sample Call Center Hierarchy 8.13.07thecallcenterpro
 
Online banking ppt
Online banking pptOnline banking ppt
Online banking pptVishnu V S
 
Electronic banking presentation
Electronic banking presentationElectronic banking presentation
Electronic banking presentationxabi951
 

Viewers also liked (7)

Beyond Profilers: Tracing Node.js Transactions
Beyond Profilers: Tracing Node.js TransactionsBeyond Profilers: Tracing Node.js Transactions
Beyond Profilers: Tracing Node.js Transactions
 
Getting Started with Rails (4)
Getting Started with Rails (4) Getting Started with Rails (4)
Getting Started with Rails (4)
 
Risk management in e banking
Risk management in e bankingRisk management in e banking
Risk management in e banking
 
Aml cft training programme
Aml cft training programmeAml cft training programme
Aml cft training programme
 
Sample Call Center Hierarchy 8.13.07
Sample Call Center Hierarchy 8.13.07Sample Call Center Hierarchy 8.13.07
Sample Call Center Hierarchy 8.13.07
 
Online banking ppt
Online banking pptOnline banking ppt
Online banking ppt
 
Electronic banking presentation
Electronic banking presentationElectronic banking presentation
Electronic banking presentation
 

Similar to ActiveRecord Callbacks & Observers, Season 2

Ruby On Rails Pitfalls
Ruby On Rails PitfallsRuby On Rails Pitfalls
Ruby On Rails PitfallsRobin Lu
 
ActiveRecord Callbacks - RORLab Season 3-5
ActiveRecord Callbacks - RORLab Season 3-5ActiveRecord Callbacks - RORLab Season 3-5
ActiveRecord Callbacks - RORLab Season 3-5창훈 정
 
ActiveRecord Validations, Season 2
ActiveRecord Validations, Season 2ActiveRecord Validations, Season 2
ActiveRecord Validations, Season 2RORLAB
 
The Dark Art of Rails Plugins (2008)
The Dark Art of Rails Plugins (2008)The Dark Art of Rails Plugins (2008)
The Dark Art of Rails Plugins (2008)lazyatom
 
Java Basics for selenium
Java Basics for seleniumJava Basics for selenium
Java Basics for seleniumapoorvams
 
Connect.Tech- Swift Memory Management
Connect.Tech- Swift Memory ManagementConnect.Tech- Swift Memory Management
Connect.Tech- Swift Memory Managementstable|kernel
 
Continuous Integration For Rails Project
Continuous Integration For Rails ProjectContinuous Integration For Rails Project
Continuous Integration For Rails ProjectLouie Zhao
 
Action Controller Overview, Season 1
Action Controller Overview, Season 1Action Controller Overview, Season 1
Action Controller Overview, Season 1RORLAB
 
PHP-05-Objects.ppt
PHP-05-Objects.pptPHP-05-Objects.ppt
PHP-05-Objects.pptrani marri
 
Active Support Core Extensions (1)
Active Support Core Extensions (1)Active Support Core Extensions (1)
Active Support Core Extensions (1)RORLAB
 
Owner - Java properties reinvented.
Owner - Java properties reinvented.Owner - Java properties reinvented.
Owner - Java properties reinvented.Luigi Viggiano
 
ActiveRecord Association (1), Season 2
ActiveRecord Association (1), Season 2ActiveRecord Association (1), Season 2
ActiveRecord Association (1), Season 2RORLAB
 
2 BytesC++ course_2014_c11_ inheritance
2 BytesC++ course_2014_c11_ inheritance2 BytesC++ course_2014_c11_ inheritance
2 BytesC++ course_2014_c11_ inheritancekinan keshkeh
 
Object Oriented Programming Tutorial.pptx
Object Oriented Programming Tutorial.pptxObject Oriented Programming Tutorial.pptx
Object Oriented Programming Tutorial.pptxethiouniverse
 

Similar to ActiveRecord Callbacks & Observers, Season 2 (20)

Ruby On Rails
Ruby On RailsRuby On Rails
Ruby On Rails
 
Ruby On Rails Pitfalls
Ruby On Rails PitfallsRuby On Rails Pitfalls
Ruby On Rails Pitfalls
 
ActiveRecord Callbacks - RORLab Season 3-5
ActiveRecord Callbacks - RORLab Season 3-5ActiveRecord Callbacks - RORLab Season 3-5
ActiveRecord Callbacks - RORLab Season 3-5
 
06.1 .Net memory management
06.1 .Net memory management06.1 .Net memory management
06.1 .Net memory management
 
ActiveRecord Validations, Season 2
ActiveRecord Validations, Season 2ActiveRecord Validations, Season 2
ActiveRecord Validations, Season 2
 
The Dark Art of Rails Plugins (2008)
The Dark Art of Rails Plugins (2008)The Dark Art of Rails Plugins (2008)
The Dark Art of Rails Plugins (2008)
 
Java Basics for selenium
Java Basics for seleniumJava Basics for selenium
Java Basics for selenium
 
Connect.Tech- Swift Memory Management
Connect.Tech- Swift Memory ManagementConnect.Tech- Swift Memory Management
Connect.Tech- Swift Memory Management
 
Continuous Integration For Rails Project
Continuous Integration For Rails ProjectContinuous Integration For Rails Project
Continuous Integration For Rails Project
 
Python_Unit_2 OOPS.pptx
Python_Unit_2  OOPS.pptxPython_Unit_2  OOPS.pptx
Python_Unit_2 OOPS.pptx
 
About Python
About PythonAbout Python
About Python
 
Action Controller Overview, Season 1
Action Controller Overview, Season 1Action Controller Overview, Season 1
Action Controller Overview, Season 1
 
PHP-05-Objects.ppt
PHP-05-Objects.pptPHP-05-Objects.ppt
PHP-05-Objects.ppt
 
Active Support Core Extensions (1)
Active Support Core Extensions (1)Active Support Core Extensions (1)
Active Support Core Extensions (1)
 
Owner - Java properties reinvented.
Owner - Java properties reinvented.Owner - Java properties reinvented.
Owner - Java properties reinvented.
 
session 24_Inheritance.ppt
session 24_Inheritance.pptsession 24_Inheritance.ppt
session 24_Inheritance.ppt
 
Active Model
Active ModelActive Model
Active Model
 
ActiveRecord Association (1), Season 2
ActiveRecord Association (1), Season 2ActiveRecord Association (1), Season 2
ActiveRecord Association (1), Season 2
 
2 BytesC++ course_2014_c11_ inheritance
2 BytesC++ course_2014_c11_ inheritance2 BytesC++ course_2014_c11_ inheritance
2 BytesC++ course_2014_c11_ inheritance
 
Object Oriented Programming Tutorial.pptx
Object Oriented Programming Tutorial.pptxObject Oriented Programming Tutorial.pptx
Object Oriented Programming Tutorial.pptx
 

More from RORLAB

Getting Started with Rails (3)
Getting Started with Rails (3) Getting Started with Rails (3)
Getting Started with Rails (3) RORLAB
 
Getting Started with Rails (2)
Getting Started with Rails (2)Getting Started with Rails (2)
Getting Started with Rails (2)RORLAB
 
Getting Started with Rails (1)
Getting Started with Rails (1)Getting Started with Rails (1)
Getting Started with Rails (1)RORLAB
 
Self join in active record association
Self join in active record associationSelf join in active record association
Self join in active record associationRORLAB
 
Asset Pipeline in Ruby on Rails
Asset Pipeline in Ruby on RailsAsset Pipeline in Ruby on Rails
Asset Pipeline in Ruby on RailsRORLAB
 
레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개
레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개
레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개RORLAB
 
Active Support Core Extension (3)
Active Support Core Extension (3)Active Support Core Extension (3)
Active Support Core Extension (3)RORLAB
 
Active Support Core Extension (2)
Active Support Core Extension (2)Active Support Core Extension (2)
Active Support Core Extension (2)RORLAB
 
Action Controller Overview, Season 2
Action Controller Overview, Season 2Action Controller Overview, Season 2
Action Controller Overview, Season 2RORLAB
 
Action View Form Helpers - 2, Season 2
Action View Form Helpers - 2, Season 2Action View Form Helpers - 2, Season 2
Action View Form Helpers - 2, Season 2RORLAB
 
Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2RORLAB
 
Layouts and Rendering in Rails, Season 2
Layouts and Rendering in Rails, Season 2Layouts and Rendering in Rails, Season 2
Layouts and Rendering in Rails, Season 2RORLAB
 
ActiveRecord Query Interface (2), Season 2
ActiveRecord Query Interface (2), Season 2ActiveRecord Query Interface (2), Season 2
ActiveRecord Query Interface (2), Season 2RORLAB
 
Active Record Query Interface (1), Season 2
Active Record Query Interface (1), Season 2Active Record Query Interface (1), Season 2
Active Record Query Interface (1), Season 2RORLAB
 
Active Record Association (2), Season 2
Active Record Association (2), Season 2Active Record Association (2), Season 2
Active Record Association (2), Season 2RORLAB
 
Rails Database Migration, Season 2
Rails Database Migration, Season 2Rails Database Migration, Season 2
Rails Database Migration, Season 2RORLAB
 
Getting started with Rails (4), Season 2
Getting started with Rails (4), Season 2Getting started with Rails (4), Season 2
Getting started with Rails (4), Season 2RORLAB
 
Getting started with Rails (3), Season 2
Getting started with Rails (3), Season 2Getting started with Rails (3), Season 2
Getting started with Rails (3), Season 2RORLAB
 
Getting started with Rails (2), Season 2
Getting started with Rails (2), Season 2Getting started with Rails (2), Season 2
Getting started with Rails (2), Season 2RORLAB
 
Getting started with Rails (1), Season 2
Getting started with Rails (1), Season 2Getting started with Rails (1), Season 2
Getting started with Rails (1), Season 2RORLAB
 

More from RORLAB (20)

Getting Started with Rails (3)
Getting Started with Rails (3) Getting Started with Rails (3)
Getting Started with Rails (3)
 
Getting Started with Rails (2)
Getting Started with Rails (2)Getting Started with Rails (2)
Getting Started with Rails (2)
 
Getting Started with Rails (1)
Getting Started with Rails (1)Getting Started with Rails (1)
Getting Started with Rails (1)
 
Self join in active record association
Self join in active record associationSelf join in active record association
Self join in active record association
 
Asset Pipeline in Ruby on Rails
Asset Pipeline in Ruby on RailsAsset Pipeline in Ruby on Rails
Asset Pipeline in Ruby on Rails
 
레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개
레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개
레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개
 
Active Support Core Extension (3)
Active Support Core Extension (3)Active Support Core Extension (3)
Active Support Core Extension (3)
 
Active Support Core Extension (2)
Active Support Core Extension (2)Active Support Core Extension (2)
Active Support Core Extension (2)
 
Action Controller Overview, Season 2
Action Controller Overview, Season 2Action Controller Overview, Season 2
Action Controller Overview, Season 2
 
Action View Form Helpers - 2, Season 2
Action View Form Helpers - 2, Season 2Action View Form Helpers - 2, Season 2
Action View Form Helpers - 2, Season 2
 
Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2
 
Layouts and Rendering in Rails, Season 2
Layouts and Rendering in Rails, Season 2Layouts and Rendering in Rails, Season 2
Layouts and Rendering in Rails, Season 2
 
ActiveRecord Query Interface (2), Season 2
ActiveRecord Query Interface (2), Season 2ActiveRecord Query Interface (2), Season 2
ActiveRecord Query Interface (2), Season 2
 
Active Record Query Interface (1), Season 2
Active Record Query Interface (1), Season 2Active Record Query Interface (1), Season 2
Active Record Query Interface (1), Season 2
 
Active Record Association (2), Season 2
Active Record Association (2), Season 2Active Record Association (2), Season 2
Active Record Association (2), Season 2
 
Rails Database Migration, Season 2
Rails Database Migration, Season 2Rails Database Migration, Season 2
Rails Database Migration, Season 2
 
Getting started with Rails (4), Season 2
Getting started with Rails (4), Season 2Getting started with Rails (4), Season 2
Getting started with Rails (4), Season 2
 
Getting started with Rails (3), Season 2
Getting started with Rails (3), Season 2Getting started with Rails (3), Season 2
Getting started with Rails (3), Season 2
 
Getting started with Rails (2), Season 2
Getting started with Rails (2), Season 2Getting started with Rails (2), Season 2
Getting started with Rails (2), Season 2
 
Getting started with Rails (1), Season 2
Getting started with Rails (1), Season 2Getting started with Rails (1), Season 2
Getting started with Rails (1), Season 2
 

Recently uploaded

How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 

Recently uploaded (20)

How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 

ActiveRecord Callbacks & Observers, Season 2

  • 1. Ror lab. season 2 - the 7th round - Active Record Callbacks & Observers October 6th, 2012 Hyoseong Choi
  • 2. Contents Validations Callbacks • The Object Life Cycle • Callbacks Overview • Validations Overview • Available Callbacks • Validation Helpers • Running Callbacks • Common Validation • Skipping Callbacks Options • Halting Execution • Conditional Validation • Relational Callbacks • Custom Validations • Conditional Callbacks • Working with Validation • Callback Classes Errors • Observers • Displaying Validation Errors • Transaction Callbacks in the View
  • 3. Life-cycle of Objects DB
  • 4. Life-cycle of Objects DB Active Record el od M
  • 5. Life-cycle of Active Record el Objects od M DB Create Save Object Delete Update
  • 6. Life-cycle of Active Record el Objects od M DB Create Save Validation Object Delete Update load
  • 7. Callbacks • Methods : protected or private • Before or after certain moments of an object’s life cycle • 6create, save, update, delete, validate, load : events • Register using a macro-style class method ★ as an ordinary method or ★ supply as a block
  • 8. Available Callbacks ★ Creating an Object ★ Updating an Object ★ Destroying an Object • before_validation • before_validation • before_destroy • after_validation • after_validation • around_destroy • before_save • before_save • after_destroy • before_create • before_update • around_create • around_update • after_create • after_update • after_save • after_save DB Validation Create Save Update Destroy
  • 9. After_find > After_initialize class User < ActiveRecord::Base   after_initialize do |user|     puts "You have initialized an object!"   end     after_find do |user|     puts "You have found an object!"   end end   >> User.new You have initialized an object! => #<User id: nil>   >> User.first You have found an object! You have initialized an object! => #<User id: 1>
  • 10. Methods Triggering Callbacks • • create create! ‘after_find’ callback • decrement! • all • destroy • first • destroy_all • find • increment! • find_all_by_attribute • save • find_by_attribute • save! • find_by_attribute! • save(:validate =>false) • toggle! • last • update • update_attribute • update_attributes • update_attributes! • valid?
  • 11. Methods Skipping Callbacks • decrement • decrement_counter • delete • delete_all • find_by_sql • increment • increment_counter • toggle • touch • update_column • update_all • update_counters
  • 12. Methods Calling Callbacks Methods Skipping Callbacks create create! decrement! decrement / ~_counter destroy delete destroy_all delete_all increment! increment / ~_counter save save! save(false) toggle! toggle update update_attribute update_column update_attributes update_all update_attributes! update_counters valid? find_by_sql touch
  • 13. Halting Execution • Queue ★ validations for model ★ registered callbacks ★ database operations • Wrapped in a Transaction ★ before_ callbacks : false or exception > stopped > ROLLBACK ★ after_ callbacks : exception > stopped > ROLLBACK
  • 15. Conditional Callbacks • As with validations ★ Using :if and :unless with a Symbol ★ Using :if and :unless with a String ★ Using :if and :unless with a Proc
  • 16. Conditional Callbacks as a symbol as a string as a Proc * multiple conditions possible!
  • 17. Callback Classes • To reuse callback methods for other models as an instance method a model object instance method
  • 18. Callback Classes as a class method
  • 19. Observers • Similar to callbacks • for the callbacks with the code that isn’t directly related the model • without changing the code of the model • ex. sending confirmation email after user registration
  • 21. Registering Observers • config/application.rb • or config/environments
  • 22. Sharing Observers as a model name
  • 23. Transaction Callbacks • after_commit or after_rollback
  • 25.  
  • 26. Macro-style class methods : As Ordinary Methods class User ActiveRecord::Base   validates :login, :email, :presence = true     before_validation :ensure_login_has_a_value     protected   def ensure_login_has_a_value     if login.nil?       self.login = email unless email.blank?     end   end
  • 27. public/protected/private parent pr class iv at child e_ m private et ho class protected public d private (sel f.)p protected rote public ed_ ct met hod http://stackoverflow.com/questions/4495078/protected-and-private-methods-in-rails
  • 28. Macro-style class methods : A Block class User ActiveRecord::Base   validates :login, :email, :presence = true     before_create do |user|     user.name = user.login.capitalize if user.name.blank?   end

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n