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
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.
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.
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.
I just wanted to use a way to declare @b to be global.
and using $b instead of @b does the trick
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With