Creating Records in the Rails Console
Learn how to create records in the database by using the Rails console.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

We are now going to create records in the Rails console. As a first step, start your Rails server with the command:

rails s

Next, open a new tab in the terminal and startup the Rails console with the command:

rails c

To create the record, I'm going to use Ruby script. If you're not familiar with this script, it's the closest one to English you're going to be able to find. I want to create ten projects automatically, so I write:

10.times do |project|

Here, I want this code to run 10 times to create ten records for me, and I have an iteration variable called project (or any other name of your choice) that will track the number of iterations. So, the first time this code runs, the value of project will be 0, the second time it will be 1, and so on.

Next, I'm going to type in the iteration script.

Project.create! (title: "Project #{project}", description: "My cool description")
end

Make sure the word Project is capitalized because we're calling a class and it's case sensitive. We're asking Ruby to create a record with each iteration. The exclamation mark after the create method is called a bang, and it gives you an exception in case there are any errors during creation. This exclamation mark is optional, but it's a good idea to use it as you can know more about the cause of error. Without the exclamation mark, the project creation process will fail silently if it runs into an error and you probably won't even know about it. Such a silent fail is good in a production site, but not in a development environment as you won't be able to spot the error easily.

Next, I'm creating values for the title attribute, and I want it to be called Project 0, Project 1 and so on, to make them each unique. To do this, I'm using the #{} syntax, and this is called a string interpolator. If you notice, I'm using the variable project, defined earlier to keep track of our iterations, as a part of the string. Now, if I don't use this interpolator, then Ruby will think it's a normal string and will insert the value "Project {project}" in the title of every record. In this sense, # tells the Ruby parser to treat the content inside the curly braces as a piece of Ruby code that needs to be executed.

The second attribute description is fairly self-explanatory and will be the same for all ten records. After pressing the Return key, my screen looks like this:

large

I can now go to the browser and refresh it to see all the records.

large