ruby-on-rails - Rails 命名空间助手

标签 ruby-on-rails ruby helper

我在 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/

相关文章:

ruby-on-rails - 用于 rails/activemerchant 的 Paypal 嵌入式支付(iframe 或其他)?

haskell - 跨守卫模式共享定义

javascript - ASP.NET MVC Razor 渲染脚本 javascript

ruby-on-rails - 使用 Steam OmniAuth gem 连接 Steam 的 OpenId 会出现 "invalid_credentials"错误

ruby-on-rails - 如何显示我已经在 Rails 中其他地方使用的数据库表中的数据

ruby-on-rails - 抽象出常见的 rspec 功能

ruby-on-rails - ruby + Mongoid : how to make a required field?

ruby - 覆盖 not_found sinatra 应用程序

ruby - ri 不在 zsh 中工作

ruby-on-rails - 如何在 rails 3 Controller 生成器中使用 `--helper` 标志?