【问题标题】:"undefined method" on custom helper method自定义辅助方法上的“未定义方法”
【发布时间】:2013-06-11 20:46:18
【问题描述】:

我的 routes.rb 文件中有以下自定义路由:

match '/security_users/:id/email_confirmation/:activation_code' => 'email_confirmation#new'

并希望创建自定义帮助程序,为指定的SecurityUser 生成上述路径。在我的 application_controler.rb 文件中,我有上面的方法:

class ApplicationController < ActionController::Base

  protect_from_forgery

  private

    def email_confirmation_path(security_user)
      "/security_users/#{security_user.id}/email_confirmation/#{security_user.activation_code}"
    end

    helper_method :email_confirmation_path

end

但是当我像这样在 /views/security_user_mailer/email_confirmation.text.erb 模板中调用它时:

<%= email_confirmation_path(@security_user) %>

我收到以下错误:

/security_users 未定义方法处的 NoMethodError #

的 `email_confirmation_path'

你能建议吗?

编辑:

您可以在下面找到流程工作流:

首先,当创建用户时,执行以下行

@security_user.send_email_confirmation

上述方法在对象模型文件中定义如下:

def send_email_confirmation
  SecurityUserMailer.email_confirmation(self).deliver
end

然后在邮件控制器中,调用下面的方法:

def email_confirmation(security_user)
  @security_user = security_user
  mail to: security_user.email, subject: 'Account Created'
end

上一个方法是使用我的模板,我需要在其中调用自定义路径生成器方法:

<%= email_confirmation_path(@security_user) %>

但我得到错误,它是未定义的。

【问题讨论】:

    标签: ruby-on-rails-3 actionmailer helper


    【解决方案1】:

    来自控制器的帮助方法在邮件程序视图中不可用。你应该把你的方法放到一个辅助模块中,例如app/helpers/application_helper.rb:

    module ApplicationHelper
    
        def email_confirmation_path(security_user)
          "/security_users/#{security_user.id}/email_confirmation/#{security_user.activation_code}"
        end
    
    end
    

    然后你应该告诉你的邮件类使用那个帮助模块(假设你的邮件是app/mailers/mailer.rb):

    class Mailer < ActionMailer::Base
      add_template_helper(ApplicationHelper)
    end
    

    之后,您将能够在邮件程序的视图中使用该帮助程序。

    附言还要注意,Ruby 中的 private 修饰符不会将对方法的访问限制在定义它的类中。子类也可以调用它。 Private 意味着一个方法不能像 obj.my_method 这样的对象被调用,而只能被隐式调用像 self 这样的 my_method

    【讨论】:

      【解决方案2】:

      该方法在 ApplicationController 中是私有的,因此子类无法访问它。你应该把它放在你班级的受保护或公共部分。

      【讨论】:

      • 嗨,我已将其公开,它给了我同样的错误。此外,正如我所阅读的,helper_method 指令使该方法对所有视图可见 - stackoverflow.com/questions/3992659/…
      • 你有没有把助手声明放在私有部分之外?
      • 您可以尝试重新启动您提到的渲染模板的 Rails 服务器和后控制器吗?
      • 谢谢,我重新启动了服务器,但没有任何改变。我在问题中添加了流程工作流 - 这是您需要的吗?
      • 奇怪.. 你能确认你的邮件控制器是从 ApplicationController 派生的吗?
      猜你喜欢
      • 2011-11-19
      • 1970-01-01
      • 2015-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多