Jump to content

The ultimate community for Ruby on Rails developers.


Define Global variables in Rails 4 and use from View

  • Please log in to reply
1 reply to this topic

#1 Amit Banerjee

Amit Banerjee


  • Members
  • 1 posts

Posted 10 August 2014 - 04:08 PM

I have a controller named expense. I want a global variable names total_expense which will be used throughout my app. I also need two other variables e.g john_expense and mark_expense.


I would like to access these two variables from the view of expense controller and the total_expense one in all views. 


What is the best way to declare these variables and how do I access them from the view? How about creating methods which can be used from view that uses these variables?

#2 Ohm



  • Moderators
  • 529 posts
  • LocationCopenhagen

Posted 11 August 2014 - 05:37 AM

If you truly just want global variables for this, you can just add them in any class (controller, model, etc) and then access them via the class.

# controller
class ExpensesController < ApplicationController

# view
John's expense is: <%= ExpensesController::JOHN_EXPENSE %> 
Mark's expense is: <%= ExpensesController::MARK_EXPENSE %> 

Blog: http://ohm.sh | Twitter: @madsohm | Work: Lokalebasen.dk

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users