How to pass data between Views and Controllers in Ruby on Rails

A view is nothing more than is an ERb template used to interpret a controller object. Ruby views are design to access not a method of a class but controller’s instance variables. If you want to pass something to a view then all you need is to set an instance variable for the controller.

Here is an example of simple controller in Ruby.

class MyController < ApplicationController
 def index
  @title = “My controller title”
   total = 10
   my_method total
 end
def my_other_method
  @other_message = “My message”
end

 private
 def my_method(counter)
  @sum += counter 
 end
end

This controller file is stored as app/controllers/my_controller.rb. In addition, this controller has an index action. This index action is defined as view in app/views/my/index.html.erb file with the following HTML.

<h3><%=@title%></h3>
<section>My counter is set to <%=@counter%></section>

From both examples above, we can see that view can

  1.        Access instance variable @title plus @counter.
  2.        Call instance methods of the instance variables
  3.        Cannot call on my_other_method due to the fact that it is never called
  4.        Cannot call on total variable since it is private to the method
  5.        Cannot call directly on any method within MyController

It is important to remember, reloading of a page in the browser will always create new instance of the class and data will be re-initialized every time in Ruby on Rails app. 

Featured pages

Ruby

Set of Ruby Object Oriented Programming Language tutorials that cover such topics as Ruby strings, …

Rails

Rails Framework tutorial teaches you how to utilize de facto framework of choice for Ruby developme…

Ruby Duck Typing

“If an object quacks like a duck just go ahead and treat it as a duck” – this fun…

Regular Expressions

Ruby uses the =~ operator to check any given string against regular expression. For example, a stri…

Credit Card Number

Every last digit of any credit card is a check sum digit that is determined by all digits in front …

Ruby Arrays

Ruby Programming Language has built in support for Arrays. Arrays help you define some of the compl…

Ruby Hashes

Hashes are very similar to arrays in Ruby and hashes interface is similar to Ruby array interface. …

Ruby Code Block

Ruby is very unique language when it comes to code blocks. You can simply pass a code block to a me…