有什么更好的方法将参数传递给Rails控制器中的过滤器?将参数传递给过滤器 - 最佳实践
编辑:根据传递给它的参数或取决于执行其操作的参数,过滤器具有不同的行为。 我在我的应用程序中有一个示例,其中一个筛选器确定数据如何排序。此过滤器具有klass参数,并调用klass.set_filter(param [:order])来确定:搜索中的顺序。
有什么更好的方法将参数传递给Rails控制器中的过滤器?将参数传递给过滤器 - 最佳实践
编辑:根据传递给它的参数或取决于执行其操作的参数,过滤器具有不同的行为。 我在我的应用程序中有一个示例,其中一个筛选器确定数据如何排序。此过滤器具有klass参数,并调用klass.set_filter(param [:order])来确定:搜索中的顺序。
你必须为此使用特效。传递参数
class FooController < ApplicationController
before_filter { |controller| controller.send(:generic_filter, "XYZ") },
:only => :edit
before_filter { |controller| controller.send(:generic_filter, "ABC") },
:only => :new
private
def generic_filter type
end
end
编辑
还有一个方法是重写的ActionController::Filters::BeforeFilter
的call
方法。
class ActionController::Filters::BeforeFilter
def call(controller, &block)
super controller, *(options[:para] || []), block
if controller.__send__(:performed?)
controller.__send__(:halt_filter_chain, method, :rendered_or_redirected)
end
end
end
现在你可以按照如下
class FooController < ApplicationController
# calls the generic_filter with param1= "foo"
before_filter :generic_filter, :para => "foo", :only => :new
# calls the generic_filter with param1= "foo" and param2="tan"
before_filter :generic_filter, :para => ["foo", "tan"], , :only => :edit
private
def generic_filter para1, para2="bar"
end
end
I -think-您正在寻找使用连续的named_scope过滤器,但我不确定。我们需要更多信息,如果这不是你需要的。
不,问题不在于模型或范围的车型改变你的before_filter规范。 – nanda 2010-02-24 18:28:18
我知道。我只是想知道是否有其他人(和更好的语义)方式来做到这一点。 – nanda 2010-02-24 22:33:23
我编辑了答案来添加另一个场景。看一看。 – 2010-02-25 01:57:28
谢谢kandada,这看起来好多了= D – nanda 2010-02-25 11:39:25