Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setup a global variable in a controller

I take inputs from users

In my index action i have:

    @b = Ece.find_by_code("#{params[:course]}")

I want to use the value stored in @b in my show action as well as in index action.

In my show action i want to do something like this:

<p><%= link_to "Forum", href="/courses/#{Course.find_by_courseCode(<%= @b %>).id}", :class=>"question_button round" %>

How can i setup @b to be global so that both these actions can use it

Note: Ece and Course are two different models

like image 909
Wasi Avatar asked Aug 21 '11 05:08

Wasi


People also ask

How do you add a global variable?

The global Keyword Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function. To create a global variable inside a function, you can use the global keyword.

How do you bring a global variable to a function?

Using the “global” Keyword. To globalize a variable, use the global keyword within a function's definition. Now changes to the variable value will be preserved.

Where do you put global variables?

Global Variables They are declared at the top of the program outside all of the functions or blocks. Declaring global variables: Global variables are usually declared outside of all of the functions and blocks, at the top of the program. They can be accessed from any portion of the program.


2 Answers

I just wanted to use a way to declare @b to be global.

and using $b instead of @b does the trick

like image 160
Wasi Avatar answered Oct 27 '22 17:10

Wasi


You could include it in a before filter like this:

before_filter :find_b, :only => [:index, :show]

# Standard controller actions here.

private
def find_b
  @b = Ece.find_by_code("#{params[:course]}")
end

Controller filters are a part of ActionController and you can find documentation on them here. In addition to before filters that run before an action there are also after filters and around filters which run around and after an action respectively.

like image 32
Devin M Avatar answered Oct 27 '22 18:10

Devin M