SQL is a great tool, but for us Rubyists, it can sometimes be hard to grasp the concepts of querying a database. I’ve decided to re-write a couple of SQL queries in Ruby to remind myself of how the rows in a table correspond to an Object and its attributes.
For this example, we’ll be modeling a crowdfunding website; we have pledges, projects, and users.
- a User has a name
- a Project has a title, category, and funding goal
- a Pledge has an amount and belongs to both a user and a project
If we were to imagine the database, each of these objects would have its own table.
- the ‘users’ table would have an ‘id’ and ‘name’ column
- the ‘projects’ table would have an ‘id,’ ‘title,’ ‘category’ and ‘funding goal’ column
- the ‘pledges’ table would have an ‘id’, ‘user_id’, and ‘project_id’ column
For our Ruby “queries” I’ve created an Object Class for User, Project, and Pledge with these same column headers as attributes for their respective classes.
Now we are ready to start our queries! I will be writing my Ruby methods so that their output is identical to the SQLite output we would get if we ran the equivalent query in SQL.
Select the title of all projects and the total amount they have raised
SQL:
1 2 3 |
|
Ruby:
1 2 3 4 5 6 7 8 9 |
|
OUTPUT: [[“World’s Best Book”, 300], [“World’s Worst Book”, 700], [“Save The Whales”, 1100], [“Save The Rhinos”, 500], [“Save The Fish”, 1000], [“World’s Best Album”, 800], [“World’s Worst Album”, 600]]
Select the title of all projects that have met their funding goal
SQL:
1 2 3 4 |
|
Ruby:
1 2 3 4 5 6 7 8 9 10 11 |
|
OUTPUT: [[“Save The Whales”], [“World’s Best Album”]]
Select the names of all users and the total amount they have pledged
SQL:
1 2 3 4 |
|
Ruby:
1 2 3 4 5 6 7 8 9 |
|
OUTPUT: [[“Matthew”, 500], [“Jonathan”, 700], [“Rebecca”, 900], [“Jordan”, 1100], [“Melissa”, 1800]]
Select the category name and the sum total of the pledge amounts of all the pledges in the book category
SQL:
1 2 3 |
|
Ruby:
1 2 3 4 5 6 7 8 9 10 11 |
|
OUTPUT: [[“books”, 1800]]
Another, more sophisticated Object-oriented model would be one in which each object had an attribute that explained their relationship to the other. For example, each pledge instance would have a user attribute and a project attribute. Each user would have an array of pledges they have made, and each project would have an array of pledges that were made towards their funding goal.
I hope this post helped you see SQL queries in a new way!