How to access a model from application.rb

Hi All

How do I access a model from within the application.rb?

What im tying to do is pull some data from a model (news in this case)
that must be displayed on each page within the entire application. I
know I could drop this into each controller, have each view pull it from
the controller, but thats repeating myself…

So whats the best way to do this (as I dont think models are visible
from within application.rb)?

Many thanks


On Mon, Jul 10, 2006, Jonathan G. wrote:

from within application.rb)?
Sure they are. Consider application.rb to be just another controller
that happens to get included in all of your other controllers.

Just access it like normal and you should be fine.


Hi All,

Just to report back, I worked out the problem I had. Just needed to
read more and get pushed in the right direction. I ended up doing it
with a partial that pulls uses an object pulled from the model.

Thanks to all for the push in the right direction



On 7/10/06, Jonathan G. [email protected] wrote:

So whats the best way to do this (as I dont think models are visible
from within application.rb)?

application.rb is a controller that all other controllers inherit from.
Models are just as visible in the application controller as any other.

There are a couple of ways to do this. Helper methods, before_filters
and a
couple of more obscure ones.

Probably using both would be benificial. You can define the method in
controller and then tell it to act as a helper method as well. Then you
it in the controller and the views.

First, use a before_filter in the application controller

class ApplicationController < ActionController::Base

before_filter :set_some_variable
helper_methods :some_variable

def some_variable

def set_some_variable
@variable = MyModel.find(:first)

This will provide a method some_variable to both views and controllers.
@variable will be set every time the controller is fired up.

Hope this helps


Many thanks