Guide to the Rails Console
Now that you've gone through the scaffold guide, let's play around with the application a little bit in the rails console.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

Now that you've gone through the scaffold guide, let's play around with the application a little bit in the rails console. To start the console, type the following command into the unix terminal:

rails c

You can type the name of any model, but the console will throw an error if that model does not exist. For example, I first did Post.all, and there was no error. Next, I did Foo.all and this threw an error because there is no model called Foo here.

large

Now, let's create a new post. To do that, run the following command:

Post.create!(title: "My cool post", image: "foo.jpg", description: "asdfasdf, asdfasdf")

This command executes a full line of SQL code and inserts these values into the database table.

large

To check if this record was created, you can run the following ActiveRecord query with this command:

Post.all

and this will display the record, and if there were any other records in the database it would show them as well.

large

You can also see how many records are there in your table with the command:

Post.all.count

You can assign the records to a variable as well.

p = Post.last

Now, you can use p to access this record. Also, you can grab the individual fields using the dot syntax.

p.title
p.image

You can update a record through this variable too. Let's say I want to update my title, and to do that run the following command:

p.update(title: "my updated post")

If you check this record, you can see the updated value.

large

You can access records and their fields or update them even without a variable. You can simply say

Post.last.title

and it will display the same values for you.

Now, what happens if I create a record without any values like this:

Post.create!()

The application will create a record, but with empty values.

large

You can delete this record with the command

Post.last.delete

If you check the database table, you'll see that it's deleted.

large

To exit the console, type ctrl-d.

So, that's how easy it is to create, update and delete records from the Rails console.