SlideShare a Scribd company logo
1 of 14
Download to read 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!

More Related Content

Viewers also liked (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
 

Similar to Rails Models

Active Record Inheritance in Rails
Active Record Inheritance in RailsActive Record Inheritance in Rails
Active Record Inheritance in Rails
Sandip Ransing
 

Similar to 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
 

Recently uploaded

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
Safe Software
 
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
Safe 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 2024
Victor Rentea
 

Recently uploaded (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