views:

109

answers:

1

I have a simple rails app that uses a master layout for all pages. I would like to have a footer in this layout that displays data from the model, so that you can see the data no matter what page you are on.

Currently I have only a single controller, with a few very simple views that are rendered into the layout with no action methods defined in the controller. The layout has something like:

<div id="footer"><%= controller.get_data %></div>

Where get_data, of course, just pulls the data from the model. This seems like a poor way to do this because I can't add more controllers without breaking the layout.

My question is: what is the best way to retrieve data from the model to be displayed in the main layout when the request could be handled by any controller rendering any view into that layout? Where should get_data be defined, or what would be a cleaner way to handle this?

+1  A: 

You can do something like this:

Define general purpose controller instance variables with accessor methods where to store current model class and instance:

class ApplicationController
  attr_accessor :current_model_class, :current_model_instance
  helper_method :current_model_class, :current_model_instance
end

In particular controller assign values to them (you can put it also in some before or after filters):

class SomeController < ApplicationController
  def index
    self.current_model_instance = SomeModel.find(params[:id])
    self.current_model_class = SomeModel
  end
end

Define the same class and instance methods in all models that will get the data for layout:

class SomeModel < ActiveRecord::Base
  def self.get_data
    # get class specific data
  end

  def get_data
    # get instance specific data
  end

end

And use it in your layout file:

<div id="footer"><%= current_model_instance.get_data %></div>

or

<div id="footer"><%= current_model_class.get_data %></div>
Raimonds Simanovskis