Learn Ruby on Rails Book

Instance variables in Rails controllers

Now let's try to display list of tasks from the database.

Open app/controllers/tasks_controller and let's change the index action.

1class TasksController < ApplicationController
2  def index
3    @tasks = Task.all
4  end
5end

Open app/views/tasks/index.html.erb file and let's pass @tasks.

1<% @tasks.each do |task| %>
2  <p>
3    <%= task.id %>
4    <%= task.title %>
5  </p>
6<% end %>

Now visit http://localhost:3000/tasks and we will see a list of tasks.

Instance variables in Rails controllers

In the controller we set @tasks which is used in the view file. A variable set in Rails controller starting with @ sign are called instance variables.

In the later chapters, when we move to API based architecture, we will change all instance variables to local variables, without the @ sign.

The specialty of instance variables is that they're available in our Rails views. We don't need to pass them explicitly to our Rails views.

That's why in the index.html.erb we are able to refer to @tasks.

Any instance variable created in a controller is available in the view file.

If the variable in the controller is not an instance variable (all variables without @ sign are not instance variables) then those variable will not be available in views.

1git add -A
2git commit -m "Added instance variables in Tasks controller"
⌘K
    to navigateEnterto select Escto close
    Previous
    Next