SlideShare una empresa de Scribd logo
1 de 9
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

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
 

La actualidad más candente (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
 

Similar 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
 

Similar 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

Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
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
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
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
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
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
 
🐬 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
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
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
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 

Último (20)

Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
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
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
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
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
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
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
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
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 

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