Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make a variable seen in all views - rails

so i have many controllers and many views.

i want my variable @random_quote to be evaluated each time every view loads up.

i tried several things in application controller(i thought it should be here?) but none of them worked.

so how do i connect these two: @random_quote.body (in view) and

@random_quote = Quote.find(:random) (in controller right?)

to bee seen through all my application?

thank you for your answers!

like image 219
user275447 Avatar asked Mar 09 '10 20:03

user275447


People also ask

Are instance variables set within a controller method accessible within a view?

Any instance variable created in a controller is available in the view file.

What is render partial in Rails?

Rails Guides describes partials this way: Partial templates - usually just called "partials" - are another device for breaking the rendering process into more manageable chunks. With a partial, you can move the code for rendering a particular piece of a response to its own file.


1 Answers

I doubt you actually need it to be accessible in all views. But you can put @random_quote = Quote.find(:random) under a method that is called with a before_filter in your ApplicationController. It will then be accessible everywhere.

Like so:

before_filter :get_random_quote
def get_random_quote
    @random_quote = Quote.find(:random)
end
like image 124
Ron Gejman Avatar answered Oct 12 '22 12:10

Ron Gejman