我应该在哪里定义一个变量(集合),以便在全部控制器视图和布局中全局访问它?在应用程序控制器或会话中的某个地方?全局访问导轨中的集合
为例
if current_user.has_role("admin")
@groups=Group.all
else
@groups=Group.all(:conditions => {:hidden => false})
end
@groups集必须是两个布局渲染(在菜单中,对于所有其他控制器)访问,并在集团控制器索引视图
我应该在哪里定义一个变量(集合),以便在全部控制器视图和布局中全局访问它?在应用程序控制器或会话中的某个地方?全局访问导轨中的集合
为例
if current_user.has_role("admin")
@groups=Group.all
else
@groups=Group.all(:conditions => {:hidden => false})
end
@groups集必须是两个布局渲染(在菜单中,对于所有其他控制器)访问,并在集团控制器索引视图
你应该把它放在您希望它可以访问的操作:
def index
if current_user.has_role("admin")
@groups = Group.all
else
@groups = Group.all(:conditions => {:hidden => false})
end
...
...
end
它将被此操作的每个布局元素访问。如果你希望它是比加的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运行load_groups方法。
如果您希望它可以在所有控制器中访问,请将上面的示例放在ApplicationController中。
如果将该方法放入应用程序helper中,您可以从控制器或视图中调用该方法。
在application_helper.rbdef membership
if current_user.has_role("admin")
@groups ||= Group.all
else
@groups ||= Group.all(:conditions => {:hidden => false})
end
@groups
end
这样,你只需要调用成员(或任何你的名字)从视图或控制器。
深化klew's example:把这个在一个before_filter
在应用程序控制器调用的方法:
@groups = current_user.has_role("admin") ? Group.all : Group.visible
的visible
方法由named_scope
的Group
模型中定义:
class Group < ActiveRecord::Base
named_scope :visible, :conditions => { :hidden => false }
end
IIRC ApplicationHelper方法不能从控制器调用,但可以包含它们。添加到你的ApplicationController:“include ApplicationHelper” – ryanb 2009-08-18 19:08:57
是的 - 我错过了。感谢Ryan的改正。 – 2009-08-18 20:05:09
或者,在ApplicationController中使用该方法,然后在ApplicationController中调用“helper_method:membership”而不是包含帮助器。 – Shadwell 2009-08-19 01:06:12