【问题标题】:Passing arguments to filters - best practices将参数传递给过滤器 - 最佳实践
【发布时间】:2010-02-24 16:35:02
【问题描述】:

在 Rails 控制器中将参数传递给过滤器的更好方法是什么?

编辑:过滤器具有不同的行为,具体取决于传递给它的参数,或者取决于执行其操作的参数。 我的应用程序中有一个示例,其中过滤器确定数据的排序方式。这个过滤器有一个 klass 参数并调用 klass.set_filter(param[:order]) 来确定搜索中的 :order。

【问题讨论】:

    标签: ruby-on-rails argument-passing filter


    【解决方案1】:

    您必须为此使用 procs。

    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::BeforeFiltercall方法。

    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
    

    现在您可以按如下方式更改 before_filter 规范

    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
    

    【讨论】:

    • 我知道。我只是想知道是否有其他(以及更好,更语义化的)方法可以做到这一点。
    • 我已经编辑了答案以添加另一个场景。看看吧。
    • 感谢 Kandada,这看起来好多了 =D
    • 好的解决方案,小注意:使用proc,你必须遵循这个语法--- before_filter(:only => :edit) { |controller| controller.send(:generic_filter, "XYZ") }
    • @kateray 此解决方案适用于 Rails 2.3.x。
    【解决方案2】:

    我-认为-您正在寻找使用连续的 named_scope 过滤器,但我不确定。如果您不需要,我们需要更多信息。

    【讨论】:

    • 不,问题不在于模型或模型的范围。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-26
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多