In this tutorial, we will be focusing on the actions of a controller and how Rails renders views based on these actions. The goal is to make you understand how to work efficiently with actions and render views in Rails.
By the end of this tutorial, you will learn:
- What actions in a controller are
- How Rails renders views
- How to work with actions and render views
Prerequisites
- Basic understanding of Ruby on Rails
- A local development environment for Ruby on Rails
Concepts
In Rails, a controller is a Ruby class which inherits from ApplicationController
and has methods. These methods are referred to as actions. Each action corresponds to a specific route defined in your routes.rb
file.
Rendering views in Rails means creating a full HTTP response to send back to the client. Rails does this by combining the controller action's output with the corresponding view template.
Best practices and tips
Here is an example of a controller with an action:
class WelcomeController < ApplicationController
def index
@message = "Hello, world!"
end
end
WelcomeController
is a class that inherits from ApplicationController
.index
is an action. When called, it sets @message
to "Hello, world!".And here is the associated view, index.html.erb
:
<h1><%= @message %></h1>
This view simply prints the content of @message
.
When you visit the route associated with the index
action, Rails will execute the index
action and render index.html.erb
, displaying "Hello, world!".
You've learned about controller actions and how Rails renders views. You've seen an example of a controller with an action and the associated view.
You can continue learning by exploring other controller actions and how to render different types of responses.
show
action. Make it display a welcome message.show
action to accept a parameter and include it in the welcome message.Solutions
class WelcomeController < ApplicationController
def show
@message = "Welcome to our site!"
end
end
In the associated show.html.erb
view:
<h1><%= @message %></h1>
class WelcomeController < ApplicationController
def show
@name = params[:name]
@message = "Welcome to our site, #{@name}!"
end
end
In the associated show.html.erb
view:
<h1><%= @message %></h1>
class WelcomeController < ApplicationController
def another_action
render :another_view
end
end
You will need to create another_view.html.erb
in the same directory as your other views.
Keep practicing with different actions and views to get a better understanding of how they work together.