【问题标题】:rails: methods from module included in controller not available in viewrails:控制器中包含的模块中的方法在视图中不可用
【发布时间】:2010-11-18 21:59:15
【问题描述】:

奇怪的事情——我在lib/ 中有这样的身份验证模块:

module Authentication
  protected

  def current_user
    User.find(1)
  end

end

在 ApplicationController 中,我包含了这个模块和所有帮助程序,但是方法 current_user 在控制器中可用,但不能从视图中使用:(我怎样才能使它工作?

【问题讨论】:

  • UPD:rails 版本 2.3.3
  • 啊,是的,最后,听起来将它作为插件而不是 /lib 中的松散文件创建对您有利。
  • return unless m < ActionController::Base 有什么意义?

标签: ruby-on-rails namespaces helpers


【解决方案1】:

如果方法是直接在控制器中定义的,则必须通过调用 helper_method :method_name 使其对视图可用。

class ApplicationController < ActionController::Base

  def current_user
    # ...
  end

  helper_method :current_user
end

有了模块,你也可以做同样的事情,但是有点棘手。

module Authentication
  def current_user
    # ...
  end

  def self.included m
    return unless m < ActionController::Base
    m.helper_method :current_user # , :any_other_helper_methods
  end
end

class ApplicationController < ActionController::Base
  include Authentication
end

啊,是的,如果你的模块是严格意义上的辅助模块,你可以按照 Lichtamberg 所说的去做。但话又说回来,您可以将其命名为 AuthenticationHelper 并将其放入 app/helpers 文件夹中。

尽管根据我自己对身份验证代码的经验,您希望控制器和视图都可以使用它。因为通常您将在控制器中处理授权。助手只对视图可用。 (我相信它们最初是作为复杂 html 结构的简写。)

【讨论】:

  • 我在 m.helper_method 上有未定义的方法 `helper_method' 用于 #<0xb139e5c>
【解决方案2】:

你用

声明了吗
  helper :foo             # => requires 'foo_helper' and includes FooHelper
  helper 'resources/foo'  # => requires 'resources/foo_helper' and includes Resources::FooHelper

在您的 ApplicationController 中?

http://railsapi.com/doc/rails-v2.3.3.1/classes/ActionController/Helpers/ClassMethods.html#M001904

【讨论】:

  • 我已经在应用程序控制器助手中:这还不够吗?
  • helper :all 只会在 app/helpers 目录(和引擎插件)中加载助手,我认为,只有当它们被命名为 something_helper.rb / SomethingHelper 时。
  • 好吧,那么您必须手动执行一些操作。见我上面的回答。
猜你喜欢
  • 1970-01-01
  • 2020-03-17
  • 1970-01-01
  • 1970-01-01
  • 2017-12-01
  • 2018-09-15
  • 2013-08-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多