Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Data Modeling with Active Record in Rails by Ha...

Data Modeling with Active Record in Rails by Hannah Howard

Data Modeling with Active Record in Rails by Hannah Howard
A presentation given on July 18th 2013 at Oversee.net at the LA Ruby & Rails Study Group Eastside/Westside Monthly Meetup.
In this workshop we will learn the basics of how data is modeled in a relational database, and how to interact with the database through Activerecord. We'll work on a simple app to keep track of a music catalog and use this example to introduce concepts like relationships, queries, and migrations. By the end, you'll have a working understanding of how to build data models to power your own apps.

The Rails view system is familiar to people who come from an HTML background. As a result, many beginning Rails programmers tend to stay focused on this component. But the core of any sizable Rails app is ActiveRecord and the model layer-- the “M” in MVC. Unfortunately, ActiveRecord is built on relational databases and SQL, concepts which are foreign to most beginning Rails programmers. After this workshop you will no longer be unfamiliar.

Other Decks in Programming

Transcript

  1. About Me: Hannah Howard Twitter: @techgirlwonder Email: [email protected] I run

    my own computer services business called Tech Girl Wonder. And I’m hiring. Thursday, July 18, 13
  2. About Me: Hannah Howard Twitter: @techgirlwonder Email: [email protected] I run

    my own computer services business called Tech Girl Wonder. And I’m hiring. I do ruby programming with Logical Reality Design, a Rails development shop. Hire us! Thursday, July 18, 13
  3. • This is my take on the subject, not the

    one true way. A FEW CAVEATS Thursday, July 18, 13
  4. • This is my take on the subject, not the

    one true way. • For the smarty pants in the room, I’m skipping over a lot. Possibly even saying things that aren’t always true. A FEW CAVEATS Thursday, July 18, 13
  5. • This is my take on the subject, not the

    one true way. • For the smarty pants in the room, I’m skipping over a lot. Possibly even saying things that aren’t always true. • There will be time for questions. A FEW CAVEATS Thursday, July 18, 13
  6. • This is my take on the subject, not the

    one true way. • For the smarty pants in the room, I’m skipping over a lot. Possibly even saying things that aren’t always true. • There will be time for questions. • This is not a lecture, only the first 15-30 minutes are. A FEW CAVEATS Thursday, July 18, 13
  7. WHY THIS TALK? • I think I’ve noticed some patterns

    in where new people get stuck learning Rails Thursday, July 18, 13
  8. WHY THIS TALK? • I think I’ve noticed some patterns

    in where new people get stuck learning Rails • I think it has to do with the parts of Rails that are closer to traditional computer programming and very different from HTML/CSS Thursday, July 18, 13
  9. WHY THIS TALK? • I think I’ve noticed some patterns

    in where new people get stuck learning Rails • I think it has to do with the parts of Rails that are closer to traditional computer programming and very different from HTML/CSS • Specifically, I think people get stuck on the ‘M’ in the MVC, i.e ActiveRecord and its connection to an SQL database. Thursday, July 18, 13
  10. STATIC WEB SITES Server Give me a page! Here’s a

    page! Client Thursday, July 18, 13
  11. STATIC WEB SITES Server Give me a page! Here’s a

    page! Client Static web page: is delivered to the user exactly as stored. Thursday, July 18, 13
  12. WEB APPLICATION List of changes sent to the model Interface

    For Receiving Input Gives Input Thursday, July 18, 13
  13. WEB APPLICATION Model Of Data Represented by App List of

    changes sent to the model Interface For Receiving Input Gives Input Thursday, July 18, 13
  14. WEB APPLICATION Data Retrieved From The Model Model Of Data

    Represented by App List of changes sent to the model Interface For Receiving Input Gives Input Thursday, July 18, 13
  15. WEB APPLICATION Information Presented To The User Data Retrieved From

    The Model Model Of Data Represented by App List of changes sent to the model Interface For Receiving Input Gives Input Thursday, July 18, 13
  16. WEB APPLICATION Information Presented To The User Data Retrieved From

    The Model Model Of Data Represented by App List of changes sent to the model Interface For Receiving Input Gives Input Sees Results Thursday, July 18, 13
  17. WEB APPLICATION Information Presented To The User Data Retrieved From

    The Model Model Of Data Represented by App List of changes sent to the model Interface For Receiving Input Server Client View Controller Gives Input Sees Results Thursday, July 18, 13
  18. WHAT IS THE MODEL? • A model of data represented

    by the application • Rails stores its data in a relational database. (usually) • You access data in relational databases with SQL queries • SQL queries are complex and hard to write • ActiveRecord is there to make that easier and “better” Thursday, July 18, 13
  19. WHAT IS A RELATIONAL DATABASE? • A series of data

    tables (like Excel spreadsheets) that are connected to each other through relationships Thursday, July 18, 13
  20. WHAT IS A RELATIONAL DATABASE? • A series of data

    tables (like Excel spreadsheets) that are connected to each other through relationships • Hint: Spend some time with Filemaker or Access Thursday, July 18, 13
  21. RELATIONAL DATABASE EXAMPLE Id Weight Stale 1 6oz TRUE 2

    8oz FALSE 3 5oz FALSE Id Name Country 1 Swiss Switzerland 2 American U.S. 3 Harvarty Denmark Id Name Address 1 Cheesetopia 123 Fake St. 2 I Love Cheese 8675 Threeonine Ave. 3 Bob’s Cheeses 1 Infinite Loop Cheese Types Cheeses Cheese Shops Thursday, July 18, 13
  22. RELATIONAL DATABASE EXAMPLE Id Weight Stale 1 6oz TRUE 2

    8oz FALSE 3 5oz FALSE Id Name Country 1 Swiss Switzerland 2 American U.S. 3 Harvarty Denmark Id Name Address 1 Cheesetopia 123 Fake St. 2 I Love Cheese 8675 Threeonine Ave. 3 Bob’s Cheeses 1 Infinite Loop Cheese Types Cheeses Cheese Shops Have Many Have Many Belongs To Belongs To Thursday, July 18, 13
  23. RELATIONAL DATABASE EXAMPLE Id Weight Stale 1 6oz TRUE 2

    8oz FALSE 3 5oz FALSE Id Name Country 1 Swiss Switzerland 2 American U.S. 3 Harvarty Denmark Id Name Address 1 Cheesetopia 123 Fake St. 2 I Love Cheese 8675 Threeonine Ave. 3 Bob’s Cheeses 1 Infinite Loop Cheese Types Cheeses Cheese Shops Id Weight Stale TypeID ShopID 1 6oz TRUE 1 2 2 8oz FALSE 3 3 3 5oz FALSE 2 1 Have Many Have Many Belongs To Belongs To Thursday, July 18, 13
  24. RELATIONAL DATABASE EXAMPLE Id Weight Stale 1 6oz TRUE 2

    8oz FALSE 3 5oz FALSE Id Name Country 1 Swiss Switzerland 2 American U.S. 3 Harvarty Denmark Id Name Address 1 Cheesetopia 123 Fake St. 2 I Love Cheese 8675 Threeonine Ave. 3 Bob’s Cheeses 1 Infinite Loop Cheese Types Cheeses Cheese Shops Id Weight Stale TypeID ShopID 1 6oz TRUE 1 2 2 8oz FALSE 3 3 3 5oz FALSE 2 1 Have Many Have Many Have Many Have Many Belongs To Belongs To Thursday, July 18, 13
  25. RELATIONAL DATABASE EXAMPLE Id Weight Stale 1 6oz TRUE 2

    8oz FALSE 3 5oz FALSE Id Name Country 1 Swiss Switzerland 2 American U.S. 3 Harvarty Denmark Id Name Address 1 Cheesetopia 123 Fake St. 2 I Love Cheese 8675 Threeonine Ave. 3 Bob’s Cheeses 1 Infinite Loop Cheese Types Cheeses Cheese Shops Id Weight Stale TypeID ShopID 1 6oz TRUE 1 2 2 8oz FALSE 3 3 3 5oz FALSE 2 1 Have Many Have Many Have Many Have Many Belongs To Belongs To TypeID ShopID 3 2 1 2 2 1 1 1 3 3 2 3 Thursday, July 18, 13
  26. SQL: STANDARD QUERY LANAGUAGE SELECT * FROM CHEESES INNER JOIN

    CHEESE_TYPES ON cheeses.cheese_type_id = cheese_types.id WHERE cheese_types.name IN [“SWISS”, “HARVARTI”] WHERE cheeses.stale = FALSE Thursday, July 18, 13
  27. SQL: STANDARD QUERY LANAGUAGE SELECT * FROM CHEESES INNER JOIN

    CHEESE_TYPES ON cheeses.cheese_type_id = cheese_types.id WHERE cheese_types.name IN [“SWISS”, “HARVARTI”] WHERE cheeses.stale = FALSE Thursday, July 18, 13
  28. ACTIVERECORD Cheese Types class CheeseType < ActiveRecord::Base has_many :cheeses has_and_belongs_to_many

    :cheese_stores attr_accessible :name, :country end Cheeses class Cheese < ActiveRecord::Base belongs_to :cheese_type belongs_to :cheese_store attr_accessible :weight, :stale end Cheese Stores class CheeseStore < ActiveRecord::Base has_many :cheeses has_and_belongs_to_many :cheese_types attr_accessible :name, :address end Thursday, July 18, 13
  29. WORKING WITH ACTIVE RECORD cheese_type.country = “France” cheese.cheese_store cheese_store.cheese_types Cheese.where(:weight

    => 4.0..10.0) Cheese.joins(:cheese_types).where(cheese_types: {name: [“SWISS”, “HAVARTI”]}).where(:stale => false) Thursday, July 18, 13
  30. WORKING WITH ACTIVE RECORD cheese_type.country = “France” cheese.cheese_store cheese_store.cheese_types Cheese.where(:weight

    => 4.0..10.0) Cheese.joins(:cheese_types).where(cheese_types: {name: [“SWISS”, “HAVARTI”]}).where(:stale => false) Thursday, July 18, 13
  31. THE KEY PIECE OF GLUE: MIGRATIONS rails generate model cheeses

    weight:decimal stale:boolean cheese_type_id:integer cheese_store_id:integer Thursday, July 18, 13
  32. THE KEY PIECE OF GLUE: MIGRATIONS rails generate model cheeses

    weight:decimal stale:boolean cheese_type_id:integer cheese_store_id:integer class CreateCheeses < ActiveRecord::Migration def change create_table :cheeses do |t| t.decimal :weight t.boolean :stale t.integer :cheese_type_id t.integer :cheese_store_id t.timestamps end end end Thursday, July 18, 13
  33. THE KEY PIECE OF GLUE: MIGRATIONS rails generate model cheeses

    weight:decimal stale:boolean cheese_type_id:integer cheese_store_id:integer class CreateCheeses < ActiveRecord::Migration def change create_table :cheeses do |t| t.decimal :weight t.boolean :stale t.integer :cheese_type_id t.integer :cheese_store_id t.timestamps end end end Oh wait, so that’s what rake db:migrate does! Thursday, July 18, 13
  34. THE KEY PIECE OF GLUE: MIGRATIONS rails generate model cheeses

    weight:decimal stale:boolean cheese_type_id:integer cheese_store_id:integer class CreateCheeses < ActiveRecord::Migration def change create_table :cheeses do |t| t.decimal :weight t.boolean :stale t.integer :cheese_type_id t.integer :cheese_store_id t.timestamps end end end Oh wait, so that’s what rake db:migrate does! Thursday, July 18, 13
  35. PREPARATION • Get in teams of 3-4. Each team will

    need one person with a laptop with Rails already setup. Preferably, you are using RVM • git clone https://github.com/hannahhoward/rb-tunes • if you have RVM, rvm gemset create rb-tunes • cd rb-tunes • bundle install • see it finished and live: rb-tunes.heroku.com Thursday, July 18, 13
  36. OUR CHALLENGE • All of the view code in your

    project is written for you • Most of the controller code is written for you • You challenge is to create the models • And if you finish that you can work on some queries in the controller • git checkout finished_version to see the final code Thursday, July 18, 13
  37. CHALLENGE 1: CREATE MODELS • You need to create four

    models: songs, artists, albums, and playlists • You will test whether you’ve finished by using RSPEC • rspec spec/models -- when everything passes, you are good to go • We’ll start this one together Thursday, July 18, 13
  38. CHALLENGE 2: QUERIES • All of the queries have been

    removed from the AlbumsController, PlaylistsController, AlbumSongsController, and PlaylistSongsController. You have to fill them in. • The ArtistsController and SongsController still have queries, use them to help you • PlaylistsSongs and AlbumsSongs are nested resources-- you’ll need to read up on these to understand how to fill in the queries Thursday, July 18, 13