CRUD


Premium Content - Free Preview

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

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.


End of Free Content Preview. Please Sign in or Sign up to buy premium content.

Contact Us