Ruby on Rails Console
Today we will talk about the Rails console and helpful command lines we can use to debug or test our Rails project or Rails API.
First of all, opening the rails console is very simple with the command.
rails c and rails console
When we are in rails c, whatever we do will interact with the actual code that it’s been written, there is another command which is very helpful if you want to test or interact with the database, editing and delete.
rails c — sandbox
rails c -sandbox allow you to work or test in an environment where anything you do on this screen will not affect the project; this is good if you want to test adding a new database without injecting the data you are using.
Finding column names of the table
Task.column_names returns the names of all the columns of the tasks table:
irb(main):006:0> Task.column_names
=> [“id”, “title”, “created_at”, “updated_at”]
Finding number of records in the table
Task.count returns the number of records in the table:
irb(main):002:0> Task.count
2 (0.1ms) SELECT COUNT(*) FROM "tasks"
3=> 0
Creating a new task using Task.create
Task.create creates and saves a new task in the database:
irb(main):003:0> Task.create
2 (0.3ms) begin transaction
3 SQL (2.8ms) INSERT INTO "tasks" ("created_at", "updated_at") VALUES (?, ?) [["created_at", "2019-01-28 17:00:26.379031"], ["updated_at", "2019-01-28 17:00:26.379031"]]
4 (11.7ms) commit transaction
5=> #<Task id: 1, title: nil, created_at: "2019-01-28 17:00:26", updated_at: "2019-01-28 17:00:26">
These are just some of the command lines that can be used in the rails console to learn more about the rails console; visit the rails guide here.