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
- Access instance variable @title plus @counter.
- Call instance methods of the instance variables
- Cannot call on my_other_method due to the fact that it is never called
- Cannot call on total variable since it is private to the method
- 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.