有人知道我为什么

undefined method `my_method' for #<MyController:0x1043a7410>

当我从ApplicationController子类中调用我的_方法("字符串")时?我的控制器看起来像

class MyController < ApplicationController
  def show
    @value = my_method(params[:string])
  end
end

还有我的助手

module ApplicationHelper
  def my_method(string)
    return string
  end
end

最后是ApplicationController

class ApplicationController < ActionController::Base
  after_filter :set_content_type
  helper :all
  helper_method :current_user_session, :current_user
  filter_parameter_logging :password
  protect_from_forgery # See ActionController::RequestForgeryProtection for details

推荐答案

您不能从控制器中呼叫助手.如果需要在多个控制器中使用该方法,则最好在ApplicationController中创建该方法.

EDIT:说清楚一点,我认为很多困惑(如果我错了,请纠正我)都源于helper :all次通话.helper :all实际上只包括视图侧任何控制器下使用的所有助手.在更早版本的Rails中,助手的名称空间决定了哪些控制器的视图可以使用助手.

我希望这有帮助.

Ruby-on-rails相关问答推荐

有什么办法能把这写清楚吗?

Trailblazor 操作 -> 集合 :attribute(has_many 通过关联) 与填充器 -> 如何填充 Reform::Form 形式的 slugs 数组?

在 Rails 中进行 Http 基本身份验证

使用带有 bootstrap-sass gem 的 Rails 4 无法让 CSS 在 Heroku 上工作

Rails:如何访问 RESTful 助手?

从 ActiveRecord 模型的集合中构建哈希

Rails 3:如何正确显示textarea中的文本?

如何在 rspec 中运行单个测试?

是否可以在 Rails 集成测试或规范中指定用户代理?

使用 RSpec 2 关闭一个规范的事务性固定装置

连接表的最佳 SQL 索引

默认呈现 JSON 而不是 HTML?

将 Rails 服务器绑定到 0.0.0.0 能给你带来什么?

rails 获取应用程序根/基本 url

Postgresql JSON 数据列不同

Ruby on Rails:如何在 select_tag 中使用默认占位符?

我的 JavaScript 模式/实践很糟糕.我应该go 哪里寻求帮助?

使用连接的 Ruby on Rails ActiveRecord 查询

Ruby 更新后:测试失败,assets资源 未声明为在生产中预编译

rails路由中资源和资源之间的区别?