【问题标题】:before_filter in few controllers少数控制器中的 before_filter
【发布时间】:2013-12-03 11:01:55
【问题描述】:

我想在以下控制器的几个特定操作中使用一个名为 :realtor_suscriberbefore_filter

realtors/registrations_controller.rb
realtors/sessons_controller.rb
pro/messages_controller.rb
pro/users_controller.rb

我在realtors/registrations_controller.rb中这样定义了realtor_suscriber

def realtor_suscriber!
....my code here...
end

当然,它不适用于其他控制器中的操作(例如 pro/messages_controller.rb)

我不想在 application_controller.rb 中定义 realtor_suscriber 因为我有一些其他控制器他们不需要这个 before_filter 并且我想避免在所有其他控制器中使用 skip_before_filter

感谢您的提前,

F.

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 before-filter


    【解决方案1】:

    可以在ApplicationController中定义realtor_suscriber!方法并添加

    before_filter :realtor_suscriber!
    

    在您需要的那些控制器中。

    【讨论】:

    • 谢谢安东,我太笨了……我一直在寻找一个太复杂的解决方案:)
    【解决方案2】:

    使用以下

    before_filter :realtor_suscriber!, :only => [:abc, :pqr]
    #Where abc, pqr are the methods for which you want filter
    

    before_filter :realtor_suscriber!, :except => [:xyz, :rst]
    #Where xyz, rst are the methods for which you don't want filter
    

    【讨论】:

      【解决方案3】:

      这个很简单,在ApplicationController中定义方法,在子控制器中作为过滤器使用即可。

      子控制器继承自 ApplicationController,因此它们始终可以访问此方法。而且你不需要在 ApplicationController 中定义这样的过滤器。

      【讨论】:

      • 谢谢Billy Chan,就像我对Anton说的那样,我太笨了...我一直在寻找一个过于复杂的解决方案:)
      【解决方案4】:

      您可以在跳过特定控制器的应用程序控制器中定义它

      def realtor_suscriber!
        if (params[:controller]=="posts" && %w(new edit show).include?(params[:action])) ||
           (params[:controller]=="comments" && %w(create update destroy).include?(params[:action])) ||
           (params[:controller]=="reviews" && %w(like share tweet).include?(params[:action]))
        return # list out all the controller/action pairs which needs to be skipped.
        #....your code here...
      end
      

      【讨论】:

      • 谢谢@Satya Kalluri,但是如何指定我想为每个控制器使用的操作?或者我不想使用 before 过滤器的特定操作。
      • 使用 params[:controller[ 和 params[:action] 和 if-else 来实现你想要的。
      • 更新了响应。看看吧。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-27
      • 2011-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多