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. These instance variables have a special property that these instance variables are available in the view file. 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"