Search
⌘K
    to navigateEnterto select Escto close

    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.

    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 the views.

    Now let's commit these changes:

    1git add -A
    2git commit -m "Added instance variables in Tasks controller"
    Previous
    Next