CRUD
Now that you created a product model and database table, you can play around with it in the terminal.
rails console
Enter rails console
(or rails c
) in the terminal to start the rails console. When developing, the console is useful for quickly testing out Rails code. On a live site, the console is useful for doing certain administrative actions without requiring any web interface. In fact, this tutorial will show you how to build a simple application just for an administrator using the console.
When you make a change in your app, enter reload!
in your console to reload the changes. If you make a major change (such as adding new gems), you'll need to restart your console by entering ctrl-c
to end it and rails c
to start it.
Optional video
create
Let's create out first product. Enter the following code in the console1:
Product.create(name: "Cow", description: "moos", price: 25)
You should see output similar to this:
(0.1ms) begin transaction
SQL (17.6ms) INSERT INTO "products" ("name", "description", "price", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?) [["name", "Cow"], ["description", "moos"], ["price", 25], ["created_at", "2015-03-24 22:00:17.916425"], ["updated_at", "2015-03-24 22:00:17.916425"]]
(1.7ms) commit transaction
=> #<Product id: 1, name: "Cow", description: "moos", price: 25, created_at: "2015-03-24 22:00:17", updated_at: "2015-03-24 22:00:17">
This means a product was created and saved to the database. Create another product with the following data:
name: "Potato" description: "starchy and nutritious" price: 2
Product.create(name: "Potato", description: "starchy and nutritious", price: 2)
new
Now let's create one more product in a slightly different way. Enter the following code:
biscuit = Product.new(name: "Biscuit", description: "Carby and delicious", price: 1)
Output:
=> #<Product id: nil, name: "Biscuit", description: "Carby and delicious", price: 1, created_at: nil, updated_at: nil>
Notice the output was much shorter than last time, without any SQL stuff. In addition, the id, created_at and updated_at values are all nil. This is because nothing has been saved to the database, the product only exists in Ruby. Sometimes you want to manipulate an item in Ruby before saving it to the database. When you're ready, enter biscuit.save
to save the product to the database.
read
There are many ways to find items in a database. The most direct way is to use the id
, a unique number that is assigned automatically to an item when it is saved to the database. To find a product with an id of 1, just enter:
Product.find 1
Output:
Product Load (0.4ms) SELECT "products".* FROM "products" ORDER BY "products"."id" ASC LIMIT 1
=> #<Product id: 1, name: "Cow", description: "moos", price: 25, ... >
This code returned a product from the database, but we can't do anything else with the product unless we assign it to a variable. Can you enter the code to do this in the challenge below and in your terminal?
If you just want the first product (i.e. the product with the smallest ID), you can enter Product.first
.
You can also find items by other properties besides ID. To do this use, the find_by
method. For example, to find an item named "Cow", enter the following code:
Product.find_by(name: "Cow")
You can get all items in a table with all
. For example Product.all
will return a collection of all products.
update
Once you have a specific product (like potato
above), you can modify it by entering:
potato.price = 3
Note that nothing has been saved to the database yet. To save this change, we need to again use save
:
potato.save
Output:
(0.8ms) begin transaction
SQL (27.4ms) UPDATE "products" SET "price" = ?, "updated_at" = ? WHERE "products"."id" = ? [["price", 3], ....
(1.4ms) commit transaction
=> true
To directly modify an item and save it to the database, use update_attributes
2 and pass it the attribute you want to change and the new value.
potato.update_attributes(description: "brown and bumpy")
This will update that products description and save it to the database. If you enter Product.find 2
you'll now see the product has new values.
delete
Let's say you don't want to sell potatoes any more. You can permanently remove this record from the database with the destroy
method:
potato.destroy
Challenge
Practice your Rails queries with a miniature version of Rails. 3
- Create a product with the following data:
name: "Potato"
description: "Brown"
price: 3 - Create a similar product as above, but name it "Tomato" with a description as "Red".
- Get the product with an "id" of 1 and change its price to 7.
- Get the product with an "id" of 2 and change its name to "A Catalog".
- Get all the products and print out each one (with
puts
).
Footnotes:
1. This is equivalent to the following syntax:
Product.create(:name => "Cow", :description => "moos", :price => 25).
2. The method 'update' does the same thing. In Ruby, there are many ways to do things.
3. This version provides the methods you need to solve the challenge, but not all Rails methods. It indexes items from 0 instead of 1.
Challenge
Enter the code that will find the product where id
is 2 and assign it to a variable called potato
.
Please sign in or sign up to submit answers.
Alternatively, you can try out Learneroo before signing up.
Challenge
Complete the challenge as described above.
Please sign in or sign up to submit answers.
Alternatively, you can try out Learneroo before signing up.