SlideShare uma empresa Scribd logo
1 de 9
Baixar para ler offline
Active record Inheritance



    ACTIVE RECORD INHERITANCE (ARI)
Oop Basics

   1. What is Active Record ?

   2. What is Inheritance ?

   3. What different Access Specifiers are in Ruby?

   4. How they changes method visibilities ?

Types of ARI

   1. Single Table Inheritanec (is_a relationship)

   2. Multiple Table Inheritanec (has_a relationship)(has_one/has_many)

Implementation step by step

Create new Rails App

       rails _2.3.8_ ari -d mysql
           create
           create app/controllers
           create app/helpers
           create app/models
          .    .    .    .

1. Single Table Inheritance (is_a relationship)

Generate Product migration

       ruby script/generate model product type:string title:string color:string
          exists app/models/
          exists test/unit/
          exists test/fixtures/
          create app/models/product.rb
          create test/unit/product_test.rb
          create test/fixtures/products.yml
          create db/migrate
          create db/migrate/20101207145844_create_products.rb


By Sandip Ransing (san2821@gmail.com) for JOsh Nights
Active record Inheritance


Migrate Database

       rake db:migrate

       (in /home/sandip/ari)
       == CreateProducts: migrating==========================================
       -- create_table(:products)
         -> 0.0018s
       == CreateProducts: migrated (0.0019s) ===================================

Ruby Console

       script/console

       Loading development environment (Rails 2.3.8)
       >> Product.all
       => []
       >> Product
       => Product(id: integer, type: string, title: string, color: string, created_at: datetime,
       updated_at: datetime)

Models

       vi app/models/pen.rb
       cat app/models/pen.rb

       class Pen < Product

       end

       vi app/models/shirt.rb
       cat app/models/shirt.rb

       class Shirt < Product

       end




By Sandip Ransing (san2821@gmail.com) for JOsh Nights
Active record Inheritance




Create initial Data

vi db/seeds.rb
cat db/seeds.rb

       # This file should contain all the record creation needed to seed the database with its
       default values.
       # The data can then be loaded with the rake db:seed (or created alongside the db with
       db:setup).
       #
       # Examples:
       #
       # cities = City.create([{ :name => 'Chicago' }, { :name => 'Copenhagen' }])
       # Major.create(:name => 'Daley', :city => cities.first)

       Pen.create(:title => 'ball pen', :color => 'red')
       Pen.create(:title => 'ink pen', :color => 'blue')

       Shirt.create(:title => 'Formal', :color => 'White')
       Shirt.create(:title => 'T-shirt', :color => 'Blue')

Load Data

       rake db:seed
       (in /home/sandip/ari)

Database Record View

       script/dbconsole



By Sandip Ransing (san2821@gmail.com) for JOsh Nights
Active record Inheritance

       mysql> select * from products;

       +----+-------+----------+-------+---------------------+---------------------+
       | id | type | title | color | created_at          | updated_at           |
       +----+-------+----------+-------+---------------------+---------------------+
       | 1 | Pen | ball pen | red | 2010-12-07 15:08:46 | 2010-12-07 15:08:46 |
       | 2 | Pen | ink pen | blue | 2010-12-07 15:08:46 | 2010-12-07 15:08:46 |
       | 3 | Shirt | Formal | White | 2010-12-07 15:08:46 | 2010-12-07 15:08:46 |
       | 4 | Shirt | T-shirt | Blue | 2010-12-07 15:08:46 | 2010-12-07 15:08:46 |
       +----+-------+----------+-------+---------------------+---------------------+
       4 rows in set (0.00 sec)

Ruby Console

       script/console

       Loading development environment (Rails 2.3.8)
       >> Product.all.collect(&:to_s)
       => ["#<Pen:0xa5907a4>", "#<Pen:0xa58ff70>", "#<Shirt:0xa58ae6c>",
       "#<Shirt:0xa58ad2c>"]

       >> Pen.all.collect(&:to_s)
       => ["#<Pen:0xa57c5d8>", "#<Pen:0xa57c2b8>"]

       >> Shirt.all.collect(&:to_s)
       => ["#<Shirt:0xa57727c>", "#<Shirt:0xa577100>"]

Rails Log View (Observe mySQL Queries)
 Product Load (0.1ms) SELECT * FROM `products`
 Product Columns (0.9ms) SHOW FIELDS FROM `products`

 Pen Columns (0.9ms) SHOW FIELDS FROM `products`
 Pen Load (0.3ms) SELECT * FROM `products` WHERE ( (`products`.`type` = 'Pen' ) )

 Shirt Columns (0.8ms) SHOW FIELDS FROM `products`
 Shirt Load (0.3ms) SELECT * FROM `products` WHERE ( (`products`.`type` = 'Shirt' ) )

Again On Console (Observe Class Hierarchy)

       script/console
       Loading development environment (Rails 2.3.8)

       >> Product.superclass
       => ActiveRecord::Base

       >> Pen.superclass
       => Product(id: integer, type: string, title: string, color: string, created_at: datetime,


By Sandip Ransing (san2821@gmail.com) for JOsh Nights
Active record Inheritance

       updated_at: datetime)

       >> Shirt.superclass
       => Product(id: integer, type: string, title: string, color: string, created_at: datetime,
       updated_at: datetime)

       >> Product.superclass.superclass
       => Object

Observe Public Method

       cat app/models/product.rb

       class Product < ActiveRecord::Base

        validates_uniqueness_of :title

        def to_param
         self.title
        end

       end

On Console

       script/console
       Loading development environment (Rails 2.3.8)

       >> p = Product.first
       => #<Pen id: 1, type: "Pen", title: "ball pen", color: "red", created_at: "2010-12-07
       15:08:46", updated_at: "2010-12-07 15:08:46">

       >> p.to_param
       => "ball pen"

Observe Private and Protected Methods

cat app/models/product.rb

       class Product < ActiveRecord::Base

        validates_uniqueness_of :title
        def to_param
         self.title
        end

        protected
        def buy

By Sandip Ransing (san2821@gmail.com) for JOsh Nights
Active record Inheritance

        end

        private
        # private methods can be called in objects only
        # can not be invoked with instance
        # not even self.identity
        # private methods in ruby accessible to childs you can't completely hide a method(similar
       to protected in java)
        def identity
          puts self.class
        end
       end

Ruby Console

       script/console
       Loading development environment (Rails 2.3.8)

       >> p = Product.first
       => #<Pen id: 1, type: "Pen", title: "ball pen", color: "red", created_at: "2010-12-07
       15:08:46", updated_at: "2010-12-07 15:08:46">

       >> p.buy
       NoMethodError: protected method `buy' called for #<Pen:0xb1878c8>

Lets access private method inside class.

       cat app/models/pen.rb

       class Pen < Product

        def buy
         identity
         "Added to cart"
        end
       end

On Console (Observer private methods can be accessed inside class)

       script/console
       Loading development environment (Rails 2.3.8)

       >> p = Pen.first
       => #<Pen id: 1, type: "Pen", title: "ball pen", color: "red", created_at: "2010-12-07
       15:08:46", updated_at: "2010-12-07 15:08:46">

       >> p.buy
       Pen

By Sandip Ransing (san2821@gmail.com) for JOsh Nights
Active record Inheritance

       => "Added to cart"

See the differenec between private and protected

       So, from within an object "a1" (an instance of Class A), you can call private methods
       only for instance of "a1" (self). And you can not call private methods of object "a2"
       (that also is of class A) - they are private to a2. But you can call protected methods of
       object "a2" since objects a1 and a2 are both of class A.
       gives following example - implementing an operator that compares one internal variable
       with variable from another class (for purposes of comparing the objects):
          def <=>(other)
            self.identity <=> other.identity
          end


   2. Multiple Table Inheritance (Polymorphic has_a relationship)

Generate migration for Purchase

ruby script/generate model purchase resource_id:integer resource_type:string user_id:integer
quantity:integer

Migrate

       rake db:migrate
       (in /home/sandip/ari)
       == CreatePurchases: migrating======================================
       -- create_table(:purchases)
         -> 0.2444s
       == CreatePurchases: migrated (0.2445s) =================================

Add polymorphic associations in Purchase and Product Model

       cat app/models/purchase.rb

       class Purchase < ActiveRecord::Base

        belongs_to :resource, :polymorphic => true
       end

cat app/models/product.rb

       class Product < ActiveRecord::Base

        has_many :purchases, :as => :resource, :dependent => :destroy
        validates_uniqueness_of :title

        def to_param

By Sandip Ransing (san2821@gmail.com) for JOsh Nights
Active record Inheritance

         self.title
        end

        protected
        def buy
        end

        private
        def identity
         puts self.class
        end
       end




On Console

       script/console
       Loading development environment (Rails 2.3.8)

       p = Pen.first
       => #<Pen id: 1, type: "Pen", title: "ball pen", color: "red", created_at: "2010-12-07
       15:08:46", updated_at: "2010-12-07 15:08:46">

       >> p.purchases
       => []

       >> p.purchases.create(:quantity => 2)
       => #<Purchase id: 1, resource_id: 1, resource_type: "Product", user_id: nil, quantity:
       2, created_at: "2010-12-08 13:47:32", updated_at: "2010-12-08 13:47:32">

       >> p.purchases
       => [#<Purchase id: 1, resource_id: 1, resource_type: "Product", user_id: nil, quantity:
       2, created_at: "2010-12-08 13:47:32", updated_at: "2010-12-08 13:47:32">]



By Sandip Ransing (san2821@gmail.com) for JOsh Nights
Active record Inheritance


       >> Purchase.first.resource
       => #<Pen id: 1, type: "Pen", title: "ball pen", color: "red", created_at: "2010-12-07
       15:08:46", updated_at: "2010-12-07 15:08:46">

End Of Session !!!

                                           ??????




By Sandip Ransing (san2821@gmail.com) for JOsh Nights

Mais conteúdo relacionado

Mais procurados

ScalikeJDBC Tutorial for Beginners
ScalikeJDBC Tutorial for BeginnersScalikeJDBC Tutorial for Beginners
ScalikeJDBC Tutorial for BeginnersKazuhiro Sera
 
Datamapper Railskonferenz 2009
Datamapper Railskonferenz 2009Datamapper Railskonferenz 2009
Datamapper Railskonferenz 2009Hussein Morsy
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Railsrstankov
 
Backbone js
Backbone jsBackbone js
Backbone jsrstankov
 
Cutting Edge Data Processing with PHP & XQuery
Cutting Edge Data Processing with PHP & XQueryCutting Edge Data Processing with PHP & XQuery
Cutting Edge Data Processing with PHP & XQueryWilliam Candillon
 
Alloy Tips & Tricks #TiLon
Alloy Tips & Tricks #TiLonAlloy Tips & Tricks #TiLon
Alloy Tips & Tricks #TiLonFokke Zandbergen
 
Practical Ruby Projects with MongoDB - Ruby Kaigi 2010
Practical Ruby Projects with MongoDB - Ruby Kaigi 2010Practical Ruby Projects with MongoDB - Ruby Kaigi 2010
Practical Ruby Projects with MongoDB - Ruby Kaigi 2010Alex Sharp
 
Web2py tutorial to create db driven application.
Web2py tutorial to create db driven application.Web2py tutorial to create db driven application.
Web2py tutorial to create db driven application.fRui Apps
 
Testing Backbone applications with Jasmine
Testing Backbone applications with JasmineTesting Backbone applications with Jasmine
Testing Backbone applications with JasmineLeon van der Grient
 
Ruby on Rails ステップアップ講座 - 大場寧子
Ruby on Rails ステップアップ講座 - 大場寧子Ruby on Rails ステップアップ講座 - 大場寧子
Ruby on Rails ステップアップ講座 - 大場寧子Yasuko Ohba
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 MinutesAzim Kurt
 
Type safe embedded domain-specific languages
Type safe embedded domain-specific languagesType safe embedded domain-specific languages
Type safe embedded domain-specific languagesArthur Xavier
 
Dig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup CairoDig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup CairoMohamed Mosaad
 
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2K
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2KZepto.js, a jQuery-compatible mobile JavaScript framework in 2K
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2KThomas Fuchs
 
Open Source Ajax Solution @OSDC.tw 2009
Open Source Ajax  Solution @OSDC.tw 2009Open Source Ajax  Solution @OSDC.tw 2009
Open Source Ajax Solution @OSDC.tw 2009Robbie Cheng
 
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legione-Legion
 
JavaScript for Flex Devs
JavaScript for Flex DevsJavaScript for Flex Devs
JavaScript for Flex DevsAaronius
 

Mais procurados (20)

ScalikeJDBC Tutorial for Beginners
ScalikeJDBC Tutorial for BeginnersScalikeJDBC Tutorial for Beginners
ScalikeJDBC Tutorial for Beginners
 
Datamapper Railskonferenz 2009
Datamapper Railskonferenz 2009Datamapper Railskonferenz 2009
Datamapper Railskonferenz 2009
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Rails
 
jQuery
jQueryjQuery
jQuery
 
Backbone js
Backbone jsBackbone js
Backbone js
 
Cutting Edge Data Processing with PHP & XQuery
Cutting Edge Data Processing with PHP & XQueryCutting Edge Data Processing with PHP & XQuery
Cutting Edge Data Processing with PHP & XQuery
 
Alloy Tips & Tricks #TiLon
Alloy Tips & Tricks #TiLonAlloy Tips & Tricks #TiLon
Alloy Tips & Tricks #TiLon
 
Practical Ruby Projects with MongoDB - Ruby Kaigi 2010
Practical Ruby Projects with MongoDB - Ruby Kaigi 2010Practical Ruby Projects with MongoDB - Ruby Kaigi 2010
Practical Ruby Projects with MongoDB - Ruby Kaigi 2010
 
Web2py tutorial to create db driven application.
Web2py tutorial to create db driven application.Web2py tutorial to create db driven application.
Web2py tutorial to create db driven application.
 
Testing Backbone applications with Jasmine
Testing Backbone applications with JasmineTesting Backbone applications with Jasmine
Testing Backbone applications with Jasmine
 
Ruby on Rails ステップアップ講座 - 大場寧子
Ruby on Rails ステップアップ講座 - 大場寧子Ruby on Rails ステップアップ講座 - 大場寧子
Ruby on Rails ステップアップ講座 - 大場寧子
 
Slickdemo
SlickdemoSlickdemo
Slickdemo
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
 
Type safe embedded domain-specific languages
Type safe embedded domain-specific languagesType safe embedded domain-specific languages
Type safe embedded domain-specific languages
 
Dig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup CairoDig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup Cairo
 
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2K
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2KZepto.js, a jQuery-compatible mobile JavaScript framework in 2K
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2K
 
Open Source Ajax Solution @OSDC.tw 2009
Open Source Ajax  Solution @OSDC.tw 2009Open Source Ajax  Solution @OSDC.tw 2009
Open Source Ajax Solution @OSDC.tw 2009
 
ES2015 workflows
ES2015 workflowsES2015 workflows
ES2015 workflows
 
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
 
JavaScript for Flex Devs
JavaScript for Flex DevsJavaScript for Flex Devs
JavaScript for Flex Devs
 

Semelhante a Active Record Inheritance Techniques

Infrastructure-as-code: bridging the gap between Devs and Ops
Infrastructure-as-code: bridging the gap between Devs and OpsInfrastructure-as-code: bridging the gap between Devs and Ops
Infrastructure-as-code: bridging the gap between Devs and OpsMykyta Protsenko
 
MongoDB World 2018: Keynote
MongoDB World 2018: KeynoteMongoDB World 2018: Keynote
MongoDB World 2018: KeynoteMongoDB
 
Burn down the silos! Helping dev and ops gel on high availability websites
Burn down the silos! Helping dev and ops gel on high availability websitesBurn down the silos! Helping dev and ops gel on high availability websites
Burn down the silos! Helping dev and ops gel on high availability websitesLindsay Holmwood
 
mongodb-introduction
mongodb-introductionmongodb-introduction
mongodb-introductionTse-Ching Ho
 
Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007Rabble .
 
Rails for Beginners - Le Wagon
Rails for Beginners - Le WagonRails for Beginners - Le Wagon
Rails for Beginners - Le WagonAlex Benoit
 
Crossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end FrameworkCrossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end FrameworkDaniel Spector
 
Lean Php Presentation
Lean Php PresentationLean Php Presentation
Lean Php PresentationAlan Pinstein
 
2013-03-23 - NoSQL Spartakiade
2013-03-23 - NoSQL Spartakiade2013-03-23 - NoSQL Spartakiade
2013-03-23 - NoSQL SpartakiadeJohannes Hoppe
 
Behavior driven oop
Behavior driven oopBehavior driven oop
Behavior driven oopPiyush Verma
 
Rails Model Basics
Rails Model BasicsRails Model Basics
Rails Model BasicsJames Gray
 
Web applications with Catalyst
Web applications with CatalystWeb applications with Catalyst
Web applications with Catalystsvilen.ivanov
 
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011Nick Sieger
 
Ruby on Rails - Introduction
Ruby on Rails - IntroductionRuby on Rails - Introduction
Ruby on Rails - IntroductionVagmi Mudumbai
 
Web Components With Rails
Web Components With RailsWeb Components With Rails
Web Components With RailsBoris Nadion
 
From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)Night Sailer
 

Semelhante a Active Record Inheritance Techniques (20)

Infrastructure-as-code: bridging the gap between Devs and Ops
Infrastructure-as-code: bridging the gap between Devs and OpsInfrastructure-as-code: bridging the gap between Devs and Ops
Infrastructure-as-code: bridging the gap between Devs and Ops
 
MongoDB World 2018: Keynote
MongoDB World 2018: KeynoteMongoDB World 2018: Keynote
MongoDB World 2018: Keynote
 
DataMapper
DataMapperDataMapper
DataMapper
 
Burn down the silos! Helping dev and ops gel on high availability websites
Burn down the silos! Helping dev and ops gel on high availability websitesBurn down the silos! Helping dev and ops gel on high availability websites
Burn down the silos! Helping dev and ops gel on high availability websites
 
mongodb-introduction
mongodb-introductionmongodb-introduction
mongodb-introduction
 
Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007
 
Rails for Beginners - Le Wagon
Rails for Beginners - Le WagonRails for Beginners - Le Wagon
Rails for Beginners - Le Wagon
 
Crossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end FrameworkCrossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end Framework
 
Introduction to RavenDB
Introduction to RavenDBIntroduction to RavenDB
Introduction to RavenDB
 
Lean Php Presentation
Lean Php PresentationLean Php Presentation
Lean Php Presentation
 
2013-03-23 - NoSQL Spartakiade
2013-03-23 - NoSQL Spartakiade2013-03-23 - NoSQL Spartakiade
2013-03-23 - NoSQL Spartakiade
 
Behavior driven oop
Behavior driven oopBehavior driven oop
Behavior driven oop
 
Rails Model Basics
Rails Model BasicsRails Model Basics
Rails Model Basics
 
Web applications with Catalyst
Web applications with CatalystWeb applications with Catalyst
Web applications with Catalyst
 
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
 
Ruby on Rails - Introduction
Ruby on Rails - IntroductionRuby on Rails - Introduction
Ruby on Rails - Introduction
 
Web Components With Rails
Web Components With RailsWeb Components With Rails
Web Components With Rails
 
From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)
 
Doctrine and NoSQL
Doctrine and NoSQLDoctrine and NoSQL
Doctrine and NoSQL
 
Android L01 - Warm Up
Android L01 - Warm UpAndroid L01 - Warm Up
Android L01 - Warm Up
 

Último

The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 

Último (20)

The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 

Active Record Inheritance Techniques

  • 1. Active record Inheritance ACTIVE RECORD INHERITANCE (ARI) Oop Basics 1. What is Active Record ? 2. What is Inheritance ? 3. What different Access Specifiers are in Ruby? 4. How they changes method visibilities ? Types of ARI 1. Single Table Inheritanec (is_a relationship) 2. Multiple Table Inheritanec (has_a relationship)(has_one/has_many) Implementation step by step Create new Rails App rails _2.3.8_ ari -d mysql create create app/controllers create app/helpers create app/models . . . . 1. Single Table Inheritance (is_a relationship) Generate Product migration ruby script/generate model product type:string title:string color:string exists app/models/ exists test/unit/ exists test/fixtures/ create app/models/product.rb create test/unit/product_test.rb create test/fixtures/products.yml create db/migrate create db/migrate/20101207145844_create_products.rb By Sandip Ransing (san2821@gmail.com) for JOsh Nights
  • 2. Active record Inheritance Migrate Database rake db:migrate (in /home/sandip/ari) == CreateProducts: migrating========================================== -- create_table(:products) -> 0.0018s == CreateProducts: migrated (0.0019s) =================================== Ruby Console script/console Loading development environment (Rails 2.3.8) >> Product.all => [] >> Product => Product(id: integer, type: string, title: string, color: string, created_at: datetime, updated_at: datetime) Models vi app/models/pen.rb cat app/models/pen.rb class Pen < Product end vi app/models/shirt.rb cat app/models/shirt.rb class Shirt < Product end By Sandip Ransing (san2821@gmail.com) for JOsh Nights
  • 3. Active record Inheritance Create initial Data vi db/seeds.rb cat db/seeds.rb # This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ :name => 'Chicago' }, { :name => 'Copenhagen' }]) # Major.create(:name => 'Daley', :city => cities.first) Pen.create(:title => 'ball pen', :color => 'red') Pen.create(:title => 'ink pen', :color => 'blue') Shirt.create(:title => 'Formal', :color => 'White') Shirt.create(:title => 'T-shirt', :color => 'Blue') Load Data rake db:seed (in /home/sandip/ari) Database Record View script/dbconsole By Sandip Ransing (san2821@gmail.com) for JOsh Nights
  • 4. Active record Inheritance mysql> select * from products; +----+-------+----------+-------+---------------------+---------------------+ | id | type | title | color | created_at | updated_at | +----+-------+----------+-------+---------------------+---------------------+ | 1 | Pen | ball pen | red | 2010-12-07 15:08:46 | 2010-12-07 15:08:46 | | 2 | Pen | ink pen | blue | 2010-12-07 15:08:46 | 2010-12-07 15:08:46 | | 3 | Shirt | Formal | White | 2010-12-07 15:08:46 | 2010-12-07 15:08:46 | | 4 | Shirt | T-shirt | Blue | 2010-12-07 15:08:46 | 2010-12-07 15:08:46 | +----+-------+----------+-------+---------------------+---------------------+ 4 rows in set (0.00 sec) Ruby Console script/console Loading development environment (Rails 2.3.8) >> Product.all.collect(&:to_s) => ["#<Pen:0xa5907a4>", "#<Pen:0xa58ff70>", "#<Shirt:0xa58ae6c>", "#<Shirt:0xa58ad2c>"] >> Pen.all.collect(&:to_s) => ["#<Pen:0xa57c5d8>", "#<Pen:0xa57c2b8>"] >> Shirt.all.collect(&:to_s) => ["#<Shirt:0xa57727c>", "#<Shirt:0xa577100>"] Rails Log View (Observe mySQL Queries) Product Load (0.1ms) SELECT * FROM `products` Product Columns (0.9ms) SHOW FIELDS FROM `products` Pen Columns (0.9ms) SHOW FIELDS FROM `products` Pen Load (0.3ms) SELECT * FROM `products` WHERE ( (`products`.`type` = 'Pen' ) ) Shirt Columns (0.8ms) SHOW FIELDS FROM `products` Shirt Load (0.3ms) SELECT * FROM `products` WHERE ( (`products`.`type` = 'Shirt' ) ) Again On Console (Observe Class Hierarchy) script/console Loading development environment (Rails 2.3.8) >> Product.superclass => ActiveRecord::Base >> Pen.superclass => Product(id: integer, type: string, title: string, color: string, created_at: datetime, By Sandip Ransing (san2821@gmail.com) for JOsh Nights
  • 5. Active record Inheritance updated_at: datetime) >> Shirt.superclass => Product(id: integer, type: string, title: string, color: string, created_at: datetime, updated_at: datetime) >> Product.superclass.superclass => Object Observe Public Method cat app/models/product.rb class Product < ActiveRecord::Base validates_uniqueness_of :title def to_param self.title end end On Console script/console Loading development environment (Rails 2.3.8) >> p = Product.first => #<Pen id: 1, type: "Pen", title: "ball pen", color: "red", created_at: "2010-12-07 15:08:46", updated_at: "2010-12-07 15:08:46"> >> p.to_param => "ball pen" Observe Private and Protected Methods cat app/models/product.rb class Product < ActiveRecord::Base validates_uniqueness_of :title def to_param self.title end protected def buy By Sandip Ransing (san2821@gmail.com) for JOsh Nights
  • 6. Active record Inheritance end private # private methods can be called in objects only # can not be invoked with instance # not even self.identity # private methods in ruby accessible to childs you can't completely hide a method(similar to protected in java) def identity puts self.class end end Ruby Console script/console Loading development environment (Rails 2.3.8) >> p = Product.first => #<Pen id: 1, type: "Pen", title: "ball pen", color: "red", created_at: "2010-12-07 15:08:46", updated_at: "2010-12-07 15:08:46"> >> p.buy NoMethodError: protected method `buy' called for #<Pen:0xb1878c8> Lets access private method inside class. cat app/models/pen.rb class Pen < Product def buy identity "Added to cart" end end On Console (Observer private methods can be accessed inside class) script/console Loading development environment (Rails 2.3.8) >> p = Pen.first => #<Pen id: 1, type: "Pen", title: "ball pen", color: "red", created_at: "2010-12-07 15:08:46", updated_at: "2010-12-07 15:08:46"> >> p.buy Pen By Sandip Ransing (san2821@gmail.com) for JOsh Nights
  • 7. Active record Inheritance => "Added to cart" See the differenec between private and protected So, from within an object "a1" (an instance of Class A), you can call private methods only for instance of "a1" (self). And you can not call private methods of object "a2" (that also is of class A) - they are private to a2. But you can call protected methods of object "a2" since objects a1 and a2 are both of class A. gives following example - implementing an operator that compares one internal variable with variable from another class (for purposes of comparing the objects): def <=>(other) self.identity <=> other.identity end 2. Multiple Table Inheritance (Polymorphic has_a relationship) Generate migration for Purchase ruby script/generate model purchase resource_id:integer resource_type:string user_id:integer quantity:integer Migrate rake db:migrate (in /home/sandip/ari) == CreatePurchases: migrating====================================== -- create_table(:purchases) -> 0.2444s == CreatePurchases: migrated (0.2445s) ================================= Add polymorphic associations in Purchase and Product Model cat app/models/purchase.rb class Purchase < ActiveRecord::Base belongs_to :resource, :polymorphic => true end cat app/models/product.rb class Product < ActiveRecord::Base has_many :purchases, :as => :resource, :dependent => :destroy validates_uniqueness_of :title def to_param By Sandip Ransing (san2821@gmail.com) for JOsh Nights
  • 8. Active record Inheritance self.title end protected def buy end private def identity puts self.class end end On Console script/console Loading development environment (Rails 2.3.8) p = Pen.first => #<Pen id: 1, type: "Pen", title: "ball pen", color: "red", created_at: "2010-12-07 15:08:46", updated_at: "2010-12-07 15:08:46"> >> p.purchases => [] >> p.purchases.create(:quantity => 2) => #<Purchase id: 1, resource_id: 1, resource_type: "Product", user_id: nil, quantity: 2, created_at: "2010-12-08 13:47:32", updated_at: "2010-12-08 13:47:32"> >> p.purchases => [#<Purchase id: 1, resource_id: 1, resource_type: "Product", user_id: nil, quantity: 2, created_at: "2010-12-08 13:47:32", updated_at: "2010-12-08 13:47:32">] By Sandip Ransing (san2821@gmail.com) for JOsh Nights
  • 9. Active record Inheritance >> Purchase.first.resource => #<Pen id: 1, type: "Pen", title: "ball pen", color: "red", created_at: "2010-12-07 15:08:46", updated_at: "2010-12-07 15:08:46"> End Of Session !!! ?????? By Sandip Ransing (san2821@gmail.com) for JOsh Nights