Passing Controller/View Data with Instance Variables

Instance variables are variables that are local to a class. They’re preceded by an @ symbol. So if you have something like this:


class Shape
@name = "Unnamed"

@sides = 0
end

@name and @sides is an instance variable. (Any fields inside the Shapes table are also instance variables.) You can do things like this:


triangle = Shape.new(:name => "Triangle", :sides => 3)
puts triangle.name # => "Triangle"
puts triangle.sides # => 3

In Rails, you can use instance variables to pass data between the controller and the view. You can write code like this:


# in shapes_controller.rb
class ShapesController < ApplicationController
def index
@shapes = Shape.find(:all)
end
end

# in views/shapes/index.html.erb

Listing Shapes

<% for shape in @shapes %>

<%=h shape.name %> (<%= h shape.sides %> sides)

<% end %>

This will list all of the shapes available in the application; you might see something like this:


Triangle (3 sides)
Circle (128 sides)
Square (4 sides)

Notice in our controller code, we assigned values from our model data to @shapes; we could then use that variable (technically, an instance variable in our ShapesController class) to access that data and display it in our view.

But how does it work? Isn’t @shapes an instance variable in the controller? It is–but Rails allows the view code to see it. In this way, Rails ties together the model, view, and controller aspects through instance variables in your controller classes.

And incidentally, this is the convention that the generated scaffolding code uses. Create any scaffolding, and it uses this same paradigm for all the default views (index, new, edit, show).

About Ashiq Alibhai

Ashiq Alibhai, PMP, has been a Rails aficionado since 2007, and developed web applications since early 2003, where he learned PHP in one summer. As the driving-force behind RailsRocket and the Launchpad project, he seeks to share the ease of development with Rails far and wide.
This entry was posted in Development and tagged , , . Bookmark the permalink.

Comments are closed.