Ruby on rails 对rails中集合的全局访问

Ruby on rails 对rails中集合的全局访问,ruby-on-rails,Ruby On Rails,我应该在哪里定义variablecollection,以便在所有控制器视图和布局中全局访问它?在应用程序控制器或会话中的某个位置 例如 if current_user.has_role("admin") @groups=Group.all else @groups=Group.all(:conditions => {:hidden => false}) end @“组”集合必须可访问,以便在“菜单中的布局”、“所有其他控制器”和“组控制器索引视图”中进行渲染,您应该在希望其可访

我应该在哪里定义variablecollection,以便在所有控制器视图和布局中全局访问它?在应用程序控制器或会话中的某个位置

例如

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

@“组”集合必须可访问,以便在“菜单中的布局”、“所有其他控制器”和“组控制器索引视图”中进行渲染,您应该在希望其可访问的位置将其付诸实施:

def index
  if current_user.has_role("admin")
    @groups = Group.all
  else
    @groups = Group.all(:conditions => {:hidden => false})
  end
  ...
  ...
end
此操作的每个布局元素都可以访问它。如果希望在一个控制器的所有操作中都可以访问它,而不是在过滤器之前添加:

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
在运行\u筛选器之前,请在运行操作方法之前加载\u组方法


如果希望在所有控制器中都可以访问该方法,则将上述示例放入ApplicationController。

如果将该方法放入应用程序中,则可以从控制器或视图调用该方法

在应用程序中\u helper.rb

def membership
  if current_user.has_role("admin")
    @groups ||= Group.all
  else
    @groups ||= Group.all(:conditions => {:hidden => false})
  end
  @groups
end
通过这种方式,您只需从视图或控制器中调用成员身份或其他名称

进一步:将其放入由应用程序控制器中的before_筛选器调用的方法中:

  @groups = current_user.has_role("admin") ? Group.all : Group.visible
visible方法由组模型上的命名范围定义:


IIRC ApplicationHelper方法不可从控制器调用,但您可以将它们包括在内,使其成为控制器。将此添加到ApplicationController:可选地包括ApplicationHelper,在ApplicationController中使用该方法,然后调用helper\u方法:在ApplicationController中加入成员身份,而不是包含该帮助者。只想写一篇关于为什么我选择了一个帮助者而不是筛选器的简介-如果您确定需要在每个请求或每个请求(1或2除外)上加载组,那么筛选器就可以了。通过使用helper方法,您可以根据需要加载组,并且在向应用程序添加功能时不必考虑这一点。
class Group < ActiveRecord::Base
  named_scope :visible, :conditions => { :hidden => false }
end