How to use Rails Console in Application

How to use Rails Console in Application

11 May 2021
0 Comments
How to use Rails Console in Application

Rails console is an IRB session built into the rails environment and can be operated by typing "rails c" in the terminal. It can be utilized to test connection methods, validations and check error messages while building a Rails application.

 

To start the rails console, run the following command run on the terminal.

 $ rails console

 

Create a user, using the User.new command. For efficiency and ease of convenience, use a variable to store the data of the new user. Create a new user variable and assign it to the User.new, for e.g: user = User.new. The return value will be the user with no attributes i.e

user_id = nil,

name =nil.

This is another way to verify if the attributes of the columns in the database are accurate.

 

A more agile way to create and save a new user to the database is to apply the method: - create as follows:

 user = User.create(name: ‘mark’,address:’America’).

This method creates and saves the object to the database.

 

Similarly, the user can update the database entry by using the command: -

 User.find(1).update(name:"peter")

With this command, the entry can be easily updated by passing the id.

 

To check the database records, the following command can be used that shows the entry of records.

User.all

 

The command to check only the first record is:

User.first

 

The command to check only the last record is:

User.last




Leave a comment: