1

当我从继承控制器(如 UsersController < ApplicationController)调用位于 ApplicationController 中的方法时,该方法的范围是什么?应用控制器还是用户控制器?

假设我有这些文件

class ApplicationController < ActionController::Base
  def method1
    method2
  end

  def method2
    ...
  end
end

class UsersController < ApplicationController
  # call method1 from here

  def method2
    ...
  end
end

正如您在此处看到的,我从 UsersController 调用 method1(位于 appcontroller 中);method1 会调用位于 UsersController 内还是 ApplicationController 内的 method2?

谢谢!

4

2 回答 2

7

新类UsersController继承了原类的所有方法ApplicationController。当您def在 中使用新方法时UsersController,它会替换父控制器中的定义,但任何其他方法仍然存在,并在调用它们时进行评估。

所以,UsersController#method1会打电话UsersController#method2。每当调用方法时,ruby 都会从当前上下文向上搜索堆栈,直到找到匹配的方法:

1)它检查UsersController#method1,什么也没找到

2)它检查ApplicationController#method1并执行它,它调用#method2

3)它检查UsersController#method2,找到并执行。

于 2013-05-20T21:44:45.363 回答
1

继承类 (UserController) 中的方法将覆盖继承类 (ApplicationController) 中的方法。

class ApplicationController < ActionController::Base
  def method1
    method2 # => 'foo'
    method3 # => 'foobar'
  end

  def method2
    'foo'
  end

  def method3
    'foobar'
  end
end

class UsersController < ApplicationController
  # call method1 from here

  def method1
    method2 # => 'bar'
    method3 # => 'foobar'
  end


  def method2
    'bar'
  end
end
于 2013-05-20T21:39:56.183 回答