如何访问命名空间视图中的 ApplicationHelper 方法?

How to access ApplicationHelper methods in namespaced views?

我在 app/helpers/application_helper.rb 中有一个 ApplicationHelper 模块 像这样定义

module ApplicationHelper
  def some_method(arg)
    
  end
end

我有我的视图文件在这里

app/views/v1/admin/messages/show.json.jbuilder

所以我正在尝试访问

some_method()

在查看文件中,但没有反映出来! 这是由于命名空间吗?或者我无法理解的内容。 如果有人解释这个概念,那就太好了。 提前致谢!

它说未定义的方法错误 可能是什么原因?

您没有包含您的控制器代码,但我们假设它最终继承自 ActionController::API(如果它是一个 API 控制器,它应该继承)。如果是这样,那就是它的根而不是命名空间等。根据 ActionController 文档:

An API Controller is different from a normal controller in the sense that by default it doesn't include a number of features that are usually required by browser access only: layouts and templates rendering, flash, assets, and so on. This makes the entire controller stack thinner, suitable for API applications. It doesn't mean you won't have such features if you need them: they're all available for you to include in your application, they're just not part of the default API controller stack.

更薄的 API 控制器的副作用之一是它们不会像标准 Rails 控制器那样自动包含助手。不过,您可以轻松地将其添加回去。

messages_controller.rb

class Api::V1::MessagesController < ActionController::API
  include ActionController::Helpers 
  helper ApplicationHelper
  
  def show
    # whatever
  end
end

app/helpers/application_helper.rb

module MessagesHelper
  def some_method(arg)
    # whatever
  end
end

app/views/messages/show.json.jbuilder

json.bogus do
  thing1: some_method('banana')
end

如果你有很多 API 控制器,你当然可以把它放在一个基本控制器中 class 它们都是这样继承的:

class Api::V1::ApiController < ActionController::API
  include ActionController::Helpers
  helper ApplicationHelper
end