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

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
 

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

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

Buy Epson EcoTank L3210 Colour Printer Online.pptx
Buy Epson EcoTank L3210 Colour Printer Online.pptxBuy Epson EcoTank L3210 Colour Printer Online.pptx
Buy Epson EcoTank L3210 Colour Printer Online.pptxEasyPrinterHelp
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlPeter Udo Diehl
 
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxUnpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxDavid Michel
 
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdfSimplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdfFIDO Alliance
 
ECS 2024 Teams Premium - Pretty Secure
ECS 2024   Teams Premium - Pretty SecureECS 2024   Teams Premium - Pretty Secure
ECS 2024 Teams Premium - Pretty SecureFemke de Vroome
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?Mark Billinghurst
 
Enterprise Knowledge Graphs - Data Summit 2024
Enterprise Knowledge Graphs - Data Summit 2024Enterprise Knowledge Graphs - Data Summit 2024
Enterprise Knowledge Graphs - Data Summit 2024Enterprise Knowledge
 
PLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. StartupsPLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. StartupsStefano
 
Agentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdfAgentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdfChristopherTHyatt
 
AI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří KarpíšekAI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří KarpíšekCzechDreamin
 
UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1DianaGray10
 
Speed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in MinutesSpeed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in Minutesconfluent
 
What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024Stephanie Beckett
 
Strategic AI Integration in Engineering Teams
Strategic AI Integration in Engineering TeamsStrategic AI Integration in Engineering Teams
Strategic AI Integration in Engineering TeamsUXDXConf
 
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka DoktorováCzechDreamin
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyJohn Staveley
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераMark Opanasiuk
 
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptxWSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptxJennifer Lim
 
IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoTAnalytics
 
Structuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessStructuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessUXDXConf
 

Recently uploaded (20)

Buy Epson EcoTank L3210 Colour Printer Online.pptx
Buy Epson EcoTank L3210 Colour Printer Online.pptxBuy Epson EcoTank L3210 Colour Printer Online.pptx
Buy Epson EcoTank L3210 Colour Printer Online.pptx
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
 
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxUnpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
 
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdfSimplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
 
ECS 2024 Teams Premium - Pretty Secure
ECS 2024   Teams Premium - Pretty SecureECS 2024   Teams Premium - Pretty Secure
ECS 2024 Teams Premium - Pretty Secure
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?
 
Enterprise Knowledge Graphs - Data Summit 2024
Enterprise Knowledge Graphs - Data Summit 2024Enterprise Knowledge Graphs - Data Summit 2024
Enterprise Knowledge Graphs - Data Summit 2024
 
PLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. StartupsPLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. Startups
 
Agentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdfAgentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdf
 
AI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří KarpíšekAI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří Karpíšek
 
UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1
 
Speed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in MinutesSpeed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in Minutes
 
What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024
 
Strategic AI Integration in Engineering Teams
Strategic AI Integration in Engineering TeamsStrategic AI Integration in Engineering Teams
Strategic AI Integration in Engineering Teams
 
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John Staveley
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджера
 
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptxWSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
 
IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024
 
Structuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessStructuring Teams and Portfolios for Success
Structuring Teams and Portfolios for Success
 

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