Accessing Data
Story
In The Hanson Basement, Dr. Hanson discusses his plans with his assistant, Dave Kemp.
Hanson: We have a new project. I met with Mr. Blackford, and he needs a machine to track his inventory.
Dave: An inventory machine? That seems very simple. How will that help you with your general goal of world domination?
Hanson: This machine will not just be focused on tracking inventory. For Mr. Blackford's own sake, we will need to make it extensible so we can add new components to help with his store. But my plan for this machine is greater than that. Once we complete this machine, we will look at the principles of its design and use them to build other machines for all sorts of purposes. Ba-Ha-Ha!
David: How will you do that?
Hanson: We will need to work out the details. But we will use solid engineering patterns so we can build similar machines for other purposes. After all, what is the purpose of any calculating tabulating machine? It needs to store and retrieve data in an easy fashion, and perform simple operations on the data. Once we have the right design worked out, everyone will want our machine! They will no longer need to hand-build their own Personal Hodgepodge of Pasta from scratch, they will be able to start out with solid architecture.
In Rails
The standard way to store website data is to use SQL - Structured Query Language. SQL can be used to quickly find the data you need, but its syntax can be verbose and a little confusing. Ruby on Rails provides "Active Record" which lets you do many standard database operations in concise "Object-oriented" Ruby code so you don't usually need to write SQL directly.
Try Rails Out
Follow these steps to get started dealing with Rails data.
(Note: "Enter" means to type the given text and hit enter.)
- Go to this Rails project on Runnable
- In the terminal on the bottom, Enter
rails console
to start the rails console. - Enter
Product.find 1
. This should return the first product, and you can view it's name and other values. - Enter
prod2 = Product.find 2
. This should assign the second product to your variableprod2
. - Enter
prod2.name
to return the name of the product. - Enter
prod2.name = "diskette"
to change the name of the product. - Enter
prod2.save
to save this change to the second product.
The Rails console lets you interact directly with an application's data, and is great for trying code out. The same commands are used to get data in an actual application.