我在 app/controllers/api/v1 中有一个 Controller Api::V1::UsersController
。
我在 app/helpers/api/v1 中有一个辅助模块 Api::V1::ErrorHelper
。
我想访问 Controller 内的辅助模块方法。所以,我调用了 Controller 的辅助方法,将模块传递给它:
class Api::V1::UsersController < ApplicationController
helper Api::V1::ErrorHelper
#other code
end
但是,当我访问 Controller 内的一种辅助方法 (respond_with_error) 时,出现以下异常:
undefined method `respond_with_error' for #<Api::V1::UsersController:0x007fad1b189578>
我如何从 Controller 访问这个助手?
(我使用的是 Rails 3.2)
谢谢。
最佳答案
Helpers 混合在 View 中,而不是在 Controller 中。例如,如果您有以下助手
module Authentication
def current_user
# ...
end
end
然后你将它包含在任何 Controller 中
helper Authentication
从操作中调用 current_user
将引发未定义的方法错误。
如果你想让一些方法对 View 和 Controller 可用,你需要一个不同的方法。定义方法并将模块作为普通模块包含在内。
class MyController < ApplicationController
include Authentication
end
并将这些方法作为助手提供。
class MyController < ApplicationController
include Authentication
helper_method :current_user
end
您还可以利用 included
Hook 。
class MyController < ApplicationController
include Authentication
end
module Authentication
def self.included(base)
base.include Helpers
base.helper Helpers
end
module Helpers
def current_user
end
end
end
关于ruby-on-rails - Rails 命名空间助手,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20133183/