Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


Ruby: Erb tag and when to use @


When do you use the @ symbol in the erb tag and when not to?

1 Answer

Variables prefixed with an @ are instance variables. You can use them if have defined the previously. Let's say you have a simple model:

class User < ActiveRecord::Base
  attr_accessible :email, :user_name

…then your controller may look like this:

class UsersController < ApplicationController
  def index
  @users = User.all

now, in your view you can use this instance variable, e.g.:

  We have <%= pluralize (@users.count, "user") %><br>
  Here's a list of all our users:
  <% @users.each do |user| %>
    <%= user.user_name %>
  <% end %>

Where these instance variables come from was a huge mistery for me when first trying to understand Rails code. The key is that you define these variables in the controller. I could just as easily have used @all_of_the_users instead of @users.

BTW: The last line has userwithout the @, because it's a local variable within the block of the .each method.