Controller is a heart of rails application as controller decides which views to render and what need to fetch from model Right? So learning controller in dept is a must have skill if you want a good grip on ruby on rails.
It's bit sounds technical but don’t worry, I’m here to explain it in the simplest way possible so you don’t get lost.
Let’s understand what it does.
What are Controllers in Rails?
Controllers act as the middlemen in your app.
They take requests from users like clicking a link or submitting a form and decide what to do next.
Let’s say you’re makign a blog. A user visits your site and wants to see all your posts. The controller’s job is to grab those posts from the database and show them on the page.
Controllers and their Actions
In Rails, controllers are Ruby classes with methods called actions. Each action does something specific. For example:
index
→ Shows all postsshow
→ Displays a single postnew
→ Prepares a form to add a new postcreate
→ Adds a new post to the database
Here’s a simple example of a PostsController
:
ruby
class PostsController < ApplicationController
def index
@posts = Post.all
end
def show
@post = Post.find(params[:id])
end
end
index
fetches all posts and stores them in@posts
.show
finds a single post based on the ID provided in the URL.
Variables like @posts are sent to views. The @ lets the data be shared with the view. Without it, the data stays only in the action. Views handle how everything looks on the screen.
How do Controllers know what to do?
This is main thing Controller does, Controllers work with routes, which act like a map for your app.
Let’s say someone visits /posts
. Rails checks your routes and figures out which controller and action to call:
ruby
get '/posts', to: 'posts#index'
This tells Rails When someone goes to `/posts`, run the `index` action in the `PostsController`.
Simple, right?
Controllers are like traffic cops they keep everything moving in the right direction. They handle:
- Taking user requests (like visiting a page or submitting a form).
- Fetching the right data from the database.
- Sending the data to the views to display it.
Without controllers, your app wouldn’t know how to respond to users.
Keep Controllers Simple
Here’s a little tip: don’t let your controllers get “fat”. If you start adding too much logic, things can get messy.
Keep your controllers clean by moving that logic to models or service objects. This makes your app easier to read and maintain.
If want to dive deeper, check out the official Rails guide on controllers.
If you learned it, Now open your Rails app, create a new controller, and see it in action.
I hope you learned something, let me know the feedback in the comments below. Thanks