Rails的ActionController如何在每个操作中执行相同的代码?

17

针对Rails专家,我想知道您会在哪里/如何执行您的Web应用程序中每个操作的相同代码?如果您可以指向一篇文章或提供一个简短的代码片段,我将不胜感激。

提前感谢任何能提供帮助的人。


单个控制器中的每个操作? - Doug Neiner
3个回答

31

在您的ApplicationController中使用一个过滤器来运行应用程序中每个操作的代码。所有控制器都是从ApplicationController继承而来的,因此将过滤器放在那里将确保过滤器得到运行。

class ApplicationController
  before_filter :verify_security_token
  def verify_security_token; puts "Run"; end;
end

15

听起来你在谈论的是过滤器

class MyController < ActionController::Base
  before_filter :execute_this_for_every_action

  def index
    @foo = @bar
  end

  def new
    @foo = @bar.to_s
  end

  def execute_this_for_every_action
    @bar = :baz
  end
end

如果您想让每个控制器都运行该过滤器,可以将过滤器放在ApplicationController上。


2
  • 如果您希望代码在每个操作之前执行,请使用before_filter

  • 如果您想每次使用操作时声明它,可以将其放在ApplicationController中,并在任何控制器中调用该方法。

另一种方法是使用帮助程序,例如:

module PersonHelper
   def eat
     {.. some code ..}
   end
end

在你的控制器中:

class MyController < ActionController::Base
  include PersonHelper

  def index
     eat
  end
end

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接