views:

59

answers:

3

where should i define a variable(collection) for it to be globally accessible both in all controller views and in layout? somewhere in Application controller or in session?

as an example

if current_user.has_role("admin")
 @groups=Group.all
else
 @groups=Group.all(:conditions => {:hidden => false})
end

@groups collection has to be accessible for rendering both in layout (in menu, for all other controllers) and in Group controller index view

A: 

You should put it in action where you want it to be accessible:

def index
  if current_user.has_role("admin")
    @groups = Group.all
  else
    @groups = Group.all(:conditions => {:hidden => false})
  end
  ...
  ...
end

It will be accessible to every layout element for this action. If you want it to be accessible in all actions of one controller than add before_filter:

class SomeController < ApplicationController
  before_filter :load_groups

  def load_groups
    if current_user.has_role("admin")
      @groups = Group.all
    else
      @groups = Group.all(:conditions => {:hidden => false})
    end
  end

  ...
end

before_filter runs load_groups method before action method is run.

And if you want it to be accessible in all controllers then put the above example in ApplicationController.

klew
A: 

If you put the method into the application helper you'd be able to call it from your controllers or views.

in application_helper.rb

def membership
  if current_user.has_role("admin")
    @groups ||= Group.all
  else
    @groups ||= Group.all(:conditions => {:hidden => false})
  end
  @groups
end

This way you just call membership (or whatever you name it) from a view or controller.

Andy Gaskell
IIRC ApplicationHelper methods are not callable from a controller, but you can include them so they are. Add this to your ApplicationController: "include ApplicationHelper"
ryanb
Yep - I missed that. Thanks for the correction Ryan.
Andy Gaskell
Alternatively, have the method in ApplicationController and then call "helper_method :membership" in ApplicationController rather than including the helper.
Shadwell
Just wanted to write a blurb about why I picked a helper over a filter - if you're sure you need to load the groups on every request (or every request except 1 or 2), then the filter would be fine. By using a helper method you load the groups as needed and it's not something you have to think about as you add functionality to your application.
Andy Gaskell
A: 

Furthering klew's example: putting this in a method called by a before_filter in your application controller:

  @groups = current_user.has_role("admin") ? Group.all : Group.visible

The visible method is defined by a named_scope on the Group model:

class Group < ActiveRecord::Base
  named_scope :visible, :conditions => { :hidden => false }
end
Ryan Bigg