SlideShare une entreprise Scribd logo
1  sur  14
Télécharger pour lire hors ligne
How to create relationships
     between models

       MeetUP @ Balabit



            June 17, 2010
          nucc@balabit.com
Model View Controller
     http://domain/:controller/:action?p1=v1&p2=v2
                           router

   Model           Controller         View




             HTML, XML, JSON, CSV, ...
Model & Database

  class Product              Table products
                              id        name
            Product object
                              1          scb
                              2        syslog-ng
                              3          zorp




                              Mysql, Pgsql, Sqlite,
     Model layer                Oracle, Mssql
     (memory)                    (hard disk)
Creating a new row

 1.
product = Product.new          class Product
                                               Table products
                                                id        name
 2.
                                                1          scb
product.name = “ssb”
                                                2        syslog-ng
 3.                                             3          zorp
product.save! / product.save     validation     4          ssb
                                        4.                  ...

                                    error
  Model                                                           Database
(memory)                                                           (disk)
Validating
class Product
  validates_presence_of :name
  validate :my_validator

 def my_validator

  if name.length < 3
    errors.add :name, “is too short”
  end

 end
end
Built-in validators
validates_uniqueness_of :username

validates_presence_of :username, :password, :email

validates_size_of :username, :password, :within => 5..15

validates_format_of :email,
   :with => /^([^@s]+)@((?:[-a-z0-9]+.)+[a-z]{2,})$/i

validates_format_of :username, :with => /^w+$/i,
   :message => "can only contain letters and numbers."

validates_confirmation_of :password

validates_inclusion_of :gender, :in => %w(male female)

validates_acceptance_of :eula
Fetch information

class Product                                  Table products
                product = find_by_name(“scb”)    id        name
                                                1          scb
                                                2        syslog-ng
                                                3          zorp
                   product.id                   4          ssb
                   #1                                       ...
Find
Product.find :all == Product.all
Product.find :first == Product.first
Product.find :last == Product.last
Product.all( :limit => 10, :offset => 3, :select => “name”, :order => “name desc” )
Product.find(1, 5, 10)
Product.all( :conditions => { :name => ["scb", "zorp"] }, :readonly => true )
Product.find_by_name(“scb”)
Product.find_by_id_and_name(1, “scb”)
Product.find_by_sql(“SELECT * FROM products”)
Product.exists?( :name => “scb” )
Product.all :conditions => [“id = ? or name = ?”, 5, “scb”]
Product.all :conditions => [“id = :id or name = :name”, {:id => 5, :name => “scb”}
Destroy
scb = Product.find_by_name “scb”
scb.delete

Product.delete_all
How to create relations?
Relations
   Product                          Owner
                 scb                      marci
                ssb


   class Product                  class Owner
     belongs_to :product_owner      has_many :products
   end                            end



   products                       owner
    id        name     owner_id    id        name
    1          scb        1        1         marci
    2          ssb        1
Has and belongs to many
Developer                                         Product
                       tia                                                  scb
                        gyp                                           ssb


class Developer                                    class Product
  has_and_belongs_to_many :products                  has_one :owner
end                                                  has_and_belongs_to_many :developers
                                                   end


    developers                developers_products            products
     id      name              developer_id   product_id       id       name      owner_id
     1        gyp                     1           1            1         scb         1
     2           tia                  1           2            2         ssb         1
Questions?
Thank you!

Contenu connexe

En vedette

Resource and view
Resource and viewResource and view
Resource and viewPapp Laszlo
 
Munkafolyamatok modellezése OPM segítségével
Munkafolyamatok modellezése OPM segítségévelMunkafolyamatok modellezése OPM segítségével
Munkafolyamatok modellezése OPM segítségévelPapp Laszlo
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven DevelopmentPapp Laszlo
 
Open Academy - Ruby
Open Academy - RubyOpen Academy - Ruby
Open Academy - RubyPapp Laszlo
 

En vedette (6)

Resource and view
Resource and viewResource and view
Resource and view
 
Munkafolyamatok modellezése OPM segítségével
Munkafolyamatok modellezése OPM segítségévelMunkafolyamatok modellezése OPM segítségével
Munkafolyamatok modellezése OPM segítségével
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Open Academy - Ruby
Open Academy - RubyOpen Academy - Ruby
Open Academy - Ruby
 
Have2do.it
Have2do.itHave2do.it
Have2do.it
 
Git thinking
Git thinkingGit thinking
Git thinking
 

Similaire à Rails Models

Active Record Inheritance in Rails
Active Record Inheritance in RailsActive Record Inheritance in Rails
Active Record Inheritance in RailsSandip Ransing
 
Scala Frustrations
Scala FrustrationsScala Frustrations
Scala Frustrationstakezoe
 
Tauhid: SQL Server Database Change Automation
Tauhid: SQL Server Database Change AutomationTauhid: SQL Server Database Change Automation
Tauhid: SQL Server Database Change AutomationSQABD
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Railsrstankov
 
From Android NDK To AOSP
From Android NDK To AOSPFrom Android NDK To AOSP
From Android NDK To AOSPMin-Yih Hsu
 
2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)
2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)
2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)JiandSon
 
Adding Security to Your Workflow With InSpec - SCaLE17x
Adding Security to Your Workflow With InSpec - SCaLE17xAdding Security to Your Workflow With InSpec - SCaLE17x
Adding Security to Your Workflow With InSpec - SCaLE17xMandi Walls
 
Writing Android Libraries
Writing Android LibrariesWriting Android Libraries
Writing Android Librariesemanuelez
 
Advanced Topics in Continuous Deployment
Advanced Topics in Continuous DeploymentAdvanced Topics in Continuous Deployment
Advanced Topics in Continuous DeploymentMike Brittain
 
مقایسه و بررسی چهارچوب ریلز
مقایسه و بررسی چهارچوب ریلزمقایسه و بررسی چهارچوب ریلز
مقایسه و بررسی چهارچوب ریلزrailsbootcamp
 
2011-02-03 LA RubyConf Rails3 TDD Workshop
2011-02-03 LA RubyConf Rails3 TDD Workshop2011-02-03 LA RubyConf Rails3 TDD Workshop
2011-02-03 LA RubyConf Rails3 TDD WorkshopWolfram Arnold
 
Pourquoi ruby et rails déchirent
Pourquoi ruby et rails déchirentPourquoi ruby et rails déchirent
Pourquoi ruby et rails déchirentNicolas Ledez
 
CUST-1 Share Document Library Extension Points
CUST-1 Share Document Library Extension PointsCUST-1 Share Document Library Extension Points
CUST-1 Share Document Library Extension PointsAlfresco Software
 
Tame Accidental Complexity with Ruby and MongoMapper
Tame Accidental Complexity with Ruby and MongoMapperTame Accidental Complexity with Ruby and MongoMapper
Tame Accidental Complexity with Ruby and MongoMapperGiordano Scalzo
 
Simplifying Persistence for Java and MongoDB with Morphia
Simplifying Persistence for Java and MongoDB with MorphiaSimplifying Persistence for Java and MongoDB with Morphia
Simplifying Persistence for Java and MongoDB with MorphiaMongoDB
 

Similaire à Rails Models (20)

Active Record Inheritance in Rails
Active Record Inheritance in RailsActive Record Inheritance in Rails
Active Record Inheritance in Rails
 
Django Good Practices
Django Good PracticesDjango Good Practices
Django Good Practices
 
Scala Frustrations
Scala FrustrationsScala Frustrations
Scala Frustrations
 
Tauhid: SQL Server Database Change Automation
Tauhid: SQL Server Database Change AutomationTauhid: SQL Server Database Change Automation
Tauhid: SQL Server Database Change Automation
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Rails
 
From Android NDK To AOSP
From Android NDK To AOSPFrom Android NDK To AOSP
From Android NDK To AOSP
 
SOLID Ruby SOLID Rails
SOLID Ruby SOLID RailsSOLID Ruby SOLID Rails
SOLID Ruby SOLID Rails
 
2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)
2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)
2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)
 
Adding Security to Your Workflow With InSpec - SCaLE17x
Adding Security to Your Workflow With InSpec - SCaLE17xAdding Security to Your Workflow With InSpec - SCaLE17x
Adding Security to Your Workflow With InSpec - SCaLE17x
 
Writing Android Libraries
Writing Android LibrariesWriting Android Libraries
Writing Android Libraries
 
Advanced Topics in Continuous Deployment
Advanced Topics in Continuous DeploymentAdvanced Topics in Continuous Deployment
Advanced Topics in Continuous Deployment
 
مقایسه و بررسی چهارچوب ریلز
مقایسه و بررسی چهارچوب ریلزمقایسه و بررسی چهارچوب ریلز
مقایسه و بررسی چهارچوب ریلز
 
Dependency injectionpreso
Dependency injectionpresoDependency injectionpreso
Dependency injectionpreso
 
2011-02-03 LA RubyConf Rails3 TDD Workshop
2011-02-03 LA RubyConf Rails3 TDD Workshop2011-02-03 LA RubyConf Rails3 TDD Workshop
2011-02-03 LA RubyConf Rails3 TDD Workshop
 
Gradle
GradleGradle
Gradle
 
Pourquoi ruby et rails déchirent
Pourquoi ruby et rails déchirentPourquoi ruby et rails déchirent
Pourquoi ruby et rails déchirent
 
CUST-1 Share Document Library Extension Points
CUST-1 Share Document Library Extension PointsCUST-1 Share Document Library Extension Points
CUST-1 Share Document Library Extension Points
 
Ruby On Rails
Ruby On RailsRuby On Rails
Ruby On Rails
 
Tame Accidental Complexity with Ruby and MongoMapper
Tame Accidental Complexity with Ruby and MongoMapperTame Accidental Complexity with Ruby and MongoMapper
Tame Accidental Complexity with Ruby and MongoMapper
 
Simplifying Persistence for Java and MongoDB with Morphia
Simplifying Persistence for Java and MongoDB with MorphiaSimplifying Persistence for Java and MongoDB with Morphia
Simplifying Persistence for Java and MongoDB with Morphia
 

Dernier

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
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
🐬 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
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
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
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
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
 
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
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
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
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Principled Technologies
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 

Dernier (20)

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)
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
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
 
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...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
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
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 

Rails Models

  • 1. How to create relationships between models MeetUP @ Balabit June 17, 2010 nucc@balabit.com
  • 2. Model View Controller http://domain/:controller/:action?p1=v1&p2=v2 router Model Controller View HTML, XML, JSON, CSV, ...
  • 3. Model & Database class Product Table products id name Product object 1 scb 2 syslog-ng 3 zorp Mysql, Pgsql, Sqlite, Model layer Oracle, Mssql (memory) (hard disk)
  • 4. Creating a new row 1. product = Product.new class Product Table products id name 2. 1 scb product.name = “ssb” 2 syslog-ng 3. 3 zorp product.save! / product.save validation 4 ssb 4. ... error Model Database (memory) (disk)
  • 5. Validating class Product validates_presence_of :name validate :my_validator def my_validator if name.length < 3 errors.add :name, “is too short” end end end
  • 6. Built-in validators validates_uniqueness_of :username validates_presence_of :username, :password, :email validates_size_of :username, :password, :within => 5..15 validates_format_of :email,    :with => /^([^@s]+)@((?:[-a-z0-9]+.)+[a-z]{2,})$/i validates_format_of :username, :with => /^w+$/i,    :message => "can only contain letters and numbers." validates_confirmation_of :password validates_inclusion_of :gender, :in => %w(male female) validates_acceptance_of :eula
  • 7. Fetch information class Product Table products product = find_by_name(“scb”) id name 1 scb 2 syslog-ng 3 zorp product.id 4 ssb #1 ...
  • 8. Find Product.find :all == Product.all Product.find :first == Product.first Product.find :last == Product.last Product.all( :limit => 10, :offset => 3, :select => “name”, :order => “name desc” ) Product.find(1, 5, 10) Product.all( :conditions => { :name => ["scb", "zorp"] }, :readonly => true ) Product.find_by_name(“scb”) Product.find_by_id_and_name(1, “scb”) Product.find_by_sql(“SELECT * FROM products”) Product.exists?( :name => “scb” ) Product.all :conditions => [“id = ? or name = ?”, 5, “scb”] Product.all :conditions => [“id = :id or name = :name”, {:id => 5, :name => “scb”}
  • 9. Destroy scb = Product.find_by_name “scb” scb.delete Product.delete_all
  • 10. How to create relations?
  • 11. Relations Product Owner scb marci ssb class Product class Owner belongs_to :product_owner has_many :products end end products owner id name owner_id id name 1 scb 1 1 marci 2 ssb 1
  • 12. Has and belongs to many Developer Product tia scb gyp ssb class Developer class Product has_and_belongs_to_many :products has_one :owner end has_and_belongs_to_many :developers end developers developers_products products id name developer_id product_id id name owner_id 1 gyp 1 1 1 scb 1 2 tia 1 2 2 ssb 1