Rails ActionController为每个操作执行相同的代码

Bri*_*asa 17 ruby-on-rails actioncontroller

对于那里的rails专家,我想知道在Web应用程序中的每个操作执行相同代码的位置和方式?如果你能指出我的文章或提供一个简短的代码片段,我将非常感激.

提前感谢任何可以提供帮助的人.

Sam*_*les 31

在ApplicationController中使用过滤器为应用程序中的每个操作运行代码.所有控制器都来自ApplicationController,因此将过滤器放在那里将确保过滤器运行.

class ApplicationController
  before_filter :verify_security_token
  def verify_security_token; puts "Run"; end;
end
Run Code Online (Sandbox Code Playgroud)


Mat*_*chu 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
Run Code Online (Sandbox Code Playgroud)

如果您希望每个控制器都运行它,您也可以将过滤器放在ApplicationController上.