- Read Tutorial
- Watch Guide Video
Now that you have a really good understanding of controllers, let's get into how we can customize some queries in Rails.
First, we can limit the number of records that we want to be displayed in the browser. If you go to the projects
page in your browser, you can see all the projects listed on it. However, what if I want only five? That's a pretty easy fix, instead of:
@projects = Project.all
In the index
method of projects_controller.rb
, we can add:
@projects = Project.limit(5)
If you go back to the browser now and hit refresh, you can see it brings up only five items from the database.
Next, if I want to only display the project with a specific title, say "Project 1." In that case, I can change the query to:
@projects=Project.where(title: "Project 1")
This will display only one project in the browser because that's the only record retrieved from the database.
Also, we can bring up all the records except "Project 1" with the code:
@projects=Project.where.not(title: "Project 1")
and this will display all the records except Project 1
for us.
Additionally, I can also string multiple conditions together. For example, I can limit the number of records to five in the above query. To do that, update the code to:
@projects = Project.where.not(title: "Project 1").limit(5)
This will limit the above list to five records, and will not contain the record with title Project 1
.
Now, if you go the terminal and scroll up a bit, you can see the query that the controller ran to execute this command.
So, even if you don't write the formal SQL query in your controller, the ActiveController class will generate a proper SQL query to run it on the database. This is a great feature because sometimes SQL queries can get messy.
In the future, say you create an application that allows users to see only those projects they are involved in, you can modify the code a bit to do that.
@projects = Project.where(user_id: current_user.id)
Though this code does nothing to our current project, it can come handy in the future for you. Essentially, what this code does is query the database for projects that match the user_id
, which in this case is the id of the current user, and retrieves only those records. This feature can be particularly useful when you don't want a user to see anything that belongs to others.
I hope this gives you an idea of how to run customized queries inside a controller. These queries can be used inside any method in any controller.