SlideShare uma empresa Scribd logo
1 de 14
Baixar para ler offline
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!

Mais conteúdo relacionado

Destaque

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
 

Destaque (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
 

Semelhante a 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
 

Semelhante a 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
 

Último

Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
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
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 
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
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
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
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
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
 

Último (20)

Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
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
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
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
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
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
 

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