How To Use Rails Console To Test Rails Models, Associations and Validations

Written by elukoye | Published 2020/06/11
Tech Story Tags: rails | ruby-on-rails | ruby | microverse | education | beginners | programming | backend | web-monetization

TLDR Using the rails console is an irb session that is built into the rails environment and is accessed by typing rails c into the terminal. It can be used to test association methods, validations and check error messages when building a rails app. A good tool to use is LUCID to help developers design their apps for their apps. We are going to build a blog with two models, a user with a name attribute and an article with a title attribute and a body attribute. Let’s build a sample blog app to see how it works.via the TL;DR App

Introduction and Definition

While learning how to build a rails application at Microverse remote school, there were numerous times where my coding partner and I were required to test if our rails association methods were working. We had to learn how to use the rails console to test this because it’s quicker than running a browser or creating tests on a separate file.
Rails console is an irb session that is built into the rails environment and is accessed by typing rails c into the terminal. It can be used to test association methods, validations and check error messages when building a rails app.
Let’s build a sample blog app to see how it works. We will start by explaining what association methods, validations and error messages are.
Association methods in rails are used to show the relationship that exists between two models. It shows how models are connected. What is a rails model? It is a Ruby class that adds records to the database through a rails migration file.
Generating a rails model automatically generates a migration file. The migration file creates tables where none existed and adds or deletes columns in the schema. Rails associations methods make it is easy to capture the relationships between models.
Active Records Validations provide validation helpers that ensure only valid data gets saved to the database. For example, in our sample blog app, we require a user to input their name to be saved to the database. By placing validation helpers in the user.rb file, a user cannot be saved if a name isn’t provided.
If a user fails to save, rails provide error messages to explain why through error messages instance methods. These instance methods return an array of error messages if any exist or an empty array if no error is found.
The errors.full_messages method returns a list of error messages that’s easy to read and that can be displayed in the view page for the user to see.
Creating a new rails app and generating rails models.
We are going to build a blog with two models, a user with a name attribute and an article with a title attribute and a body attribute. To get started, open your terminal and enter the command rails new blog_app.
This command generates folders and files that are needed by a new rails app.
Next, cd into the blog_app folder and let’s create our models. First, we create a User model, then an Article Model.
The command used to create models in rails begins with rails g model followed by the model’s name (e.g User) then the column name: type of data (e.g name: string)
rails g model (the model name) (nameofcolumn1:data-type) (nameofcolumn2:data-type)
In our case:- rails g model User name: string
This command creates a migration file, test for the model and fixtures used to add data when testing your models. We created a user model with one attribute which is the user’s name. This is the same process that we will use to create the Article model which will have two columns, title and body, both of type string
:- rails g model Article title: string body: string
To view your migration file, navigate to app/db/migrate. This gives you a glimpse of what tables and columns your migration file will create in your database schema. The files appear in the order in which they were generated. Note that I said this is a glimpse of what will be created meaning the tables haven’t been created yet.
To create them simply type the rails db: migrate command which migrates your files and creates the user table with the name column and the articles table with the title and body columns in the database.
In case a mistake is made while generating the rails model then the rails destroy model (model name) command can be used to undo the rails g model command. It reverses the rails g model command and removes the migration files that had been generated before a rails db: migrate command is run.
If you had already run the rails db: migration command then simply do a rails db: rollback to drop the table in the schema, delete the migration file in the app/db/migrate folder then destroy the rails model with the rails destroy command above.
Relationship between User and Article models.
In a blog application, a user can write many articles but an article can only belong to one User. Developers use ERB diagrams to visually show this relationship while designing databases for their apps. A good tool to use is LUCID Chart.

Connecting the models by adding the has_many association method.

Next, add the has_many association method to your model. Go to blog_app/app/models/user.rb and add has_many :articles. This method is made available through inheritance from the Application Record class in rails.
Testing has_many method using Rails Console
At this point, we can start testing our models and association methods.
1. Type rails c into your terminal to access your irb session
2. Check if a user has already been created using User.all
This command uses SQLite queries through active records to check if any user exists in the users' table. Nothing is returned since we haven’t created a user for our application.
3. Create a user, use the User.new command. For ease of use, we will use a variable to store the data of our new user. Create a user variable and assign it to User.new e.g user = User.new. T
he return value will be a user with no attributes i.e user_id = nil, name =nil e.t.c.This is another way to check if the columns a.k.a attributes in the database are correct.
Fill in the attributes as follows user = User.new(name: “Zoe”)
This command creates a user called Zoe. If you type user.id the output will be nil because the user has been created but not saved to the database. Therefore, we must do user.save to save the user to the database. Now try query for the user’s id by typing the command user.id, the output will be 1.
Congratulations, you have created your first user.
In the image above, begin transaction indicates that the process of saving the user to the database has begun. If everything is ok the transaction is committed and the boolean value true is returned.
4. A faster way to create and save a new user to the database is to use the method create as follows user = User.create(name: ‘Henry’). This method does the double work of creating and saving the object to the database.

Adding Validations to Models

An important aspect of creating rails models is validating the presence of those model’s attributes. This prevents invalid objects from being saved to the database. The image below shows a user without a name attribute being saved successfully to the database.
I can't think of an instance where we would want to build an app that doesn't require a particular attribute, yet the attribute exists in the database as an empty column.
5. Open your user.rb file add the following validates : name, presence: true.
This validation helper ensures that nothing is saved to the database if a name attribute is not present.
Create another user with User.new. Don't fill in the user’s name, then do a user. save. The output result should be false meaning our user failed to save.

Checking for errors when our models fail to save

To check why our database save was false, do user.errors.any?
Output on the terminal should be the boolean value true indicating that errors were found. To list the errors do user.errors.full_messages which returns a list of errors as below:

Adding the belongs_to association method

Now, we add a belongs_to method to the Article model. Without it, the relationship between the user and article models is half complete.
Open article.rb and add belongs_to: user inside the class, add validations as well i.e validates: title, presence: true and validates: body, presence: true
Create a new article using the new method and save it to the database. The article saves successfully.
Rails console can also be used to query the database for all the articles that have been created or all the users that exist in the database using the count method.
If we want a list of articles created by the first user, we can do user = User.first to get the user whose user_id == 1 then do user.articles which returns an array of articles created by the first user.
In our case, we get an error saying that there is no column in the database with the column name articles.user_id
Having a belongs_to method doesn’t show which user authored which article. A user_id is needed in the article table to map each article to a particular user. This is done by adding a user_id column as a foreign key in the article’s table.
In rails 5 and above use the command rails generate migration add_references_to_articles user: references
Do a rails db: migrate to migrate the file that was generated. If you open the schema, you will see that a new column user_id of type integer has been added. The schema will be modified as below:
We can set the first article we created in the console to belong to the first user as follows:
  • article = Article.first which gets the first article in the database and stores it in the article variable.
  • article.user_id shows us which user’s id this article belongs to which is null currently.
  • article.user_id = 1 sets the article to belong to the first user’s id.
  • article. save saves the article
Now we can type user = User.first then user.articles to give us a list of articles created by the first user. You can also query the database for the total number of articles owned by the first user with user.articles.count

Conclusion

I believe you now have a better understanding of the rails console and I hope that it doesn’t feel as scary to open your terminal, do a rails c. Start playing with your app models and methods.
There are other methods that can be used in the console to test for different things such as the find method, but I hope this inspires you to learn more about the rails console.
The source code for this tutorial can be found on my GitHub, leave an ⭐️ on the repo if you like the tutorial or found it helpful.

Written by elukoye | Using tech to bring my creative imagination into physical reality.
Published by HackerNoon on 2020/06/11