SlideShare a Scribd company logo
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

More Related Content

What's hot

ScalikeJDBC Tutorial for Beginners
ScalikeJDBC Tutorial for BeginnersScalikeJDBC Tutorial for Beginners
ScalikeJDBC Tutorial for Beginners
Kazuhiro Sera
 
Datamapper Railskonferenz 2009
Datamapper Railskonferenz 2009Datamapper Railskonferenz 2009
Datamapper Railskonferenz 2009
Hussein Morsy
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Rails
rstankov
 
jQuery
jQueryjQuery
jQuery
Vishwa Mohan
 
Backbone js
Backbone jsBackbone js
Backbone js
rstankov
 
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
William Candillon
 
Alloy Tips & Tricks #TiLon
Alloy Tips & Tricks #TiLonAlloy Tips & Tricks #TiLon
Alloy Tips & Tricks #TiLon
Fokke 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 Jasmine
Leon van der Grient
 
Ruby on Rails ステップアップ講座 - 大場寧子
Ruby on Rails ステップアップ講座 - 大場寧子Ruby on Rails ステップアップ講座 - 大場寧子
Ruby on Rails ステップアップ講座 - 大場寧子
Yasuko Ohba
 
Slickdemo
SlickdemoSlickdemo
Slickdemo
Knoldus Inc.
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
Azim Kurt
 
Type safe embedded domain-specific languages
Type safe embedded domain-specific languagesType safe embedded domain-specific languages
Type safe embedded domain-specific languages
Arthur 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 Cairo
Mohamed 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 2009
Robbie Cheng
 
ES2015 workflows
ES2015 workflowsES2015 workflows
ES2015 workflows
Jarrod Overson
 
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
e-Legion
 
JavaScript for Flex Devs
JavaScript for Flex DevsJavaScript for Flex Devs
JavaScript for Flex Devs
Aaronius
 

What's hot (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 to Active Record Inheritance in Rails

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
Mykyta Protsenko
 
MongoDB World 2018: Keynote
MongoDB World 2018: KeynoteMongoDB World 2018: Keynote
MongoDB World 2018: Keynote
MongoDB
 
DataMapper
DataMapperDataMapper
DataMapper
Yehuda Katz
 
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
Lindsay Holmwood
 
mongodb-introduction
mongodb-introductionmongodb-introduction
mongodb-introduction
Tse-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 2007
Rabble .
 
Rails for Beginners - Le Wagon
Rails for Beginners - Le WagonRails for Beginners - Le Wagon
Rails for Beginners - Le Wagon
Alex 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 Framework
Daniel Spector
 
Introduction to RavenDB
Introduction to RavenDBIntroduction to RavenDB
Introduction to RavenDB
Sasha Goldshtein
 
Lean Php Presentation
Lean Php PresentationLean Php Presentation
Lean Php Presentation
Alan Pinstein
 
2013-03-23 - NoSQL Spartakiade
2013-03-23 - NoSQL Spartakiade2013-03-23 - NoSQL Spartakiade
2013-03-23 - NoSQL Spartakiade
Johannes Hoppe
 
Behavior driven oop
Behavior driven oopBehavior driven oop
Behavior driven oop
Piyush Verma
 
Rails Model Basics
Rails Model BasicsRails Model Basics
Rails Model Basics
James 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 - Introduction
Vagmi Mudumbai
 
Web Components With Rails
Web Components With RailsWeb Components With Rails
Web Components With Rails
Boris Nadion
 
From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)Night Sailer
 
Doctrine and NoSQL
Doctrine and NoSQLDoctrine and NoSQL
Doctrine and NoSQL
Benjamin Eberlei
 
Android L01 - Warm Up
Android L01 - Warm UpAndroid L01 - Warm Up
Android L01 - Warm Up
Mohammad Shaker
 

Similar to Active Record Inheritance in Rails (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
 

Recently uploaded

How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website
Pixlogix Infotech
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
Neo4j
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
Rohit Gautam
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
Neo4j
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
ThomasParaiso2
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
Alex Pruden
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Malak Abu Hammad
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 

Recently uploaded (20)

How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 

Active Record Inheritance in Rails

  • 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